-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
max.go
87 lines (83 loc) · 1.59 KB
/
max.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package linq
import "golang.org/x/exp/constraints"
// Maxby returns the maximum value in a sequence of values.
func Max[T constraints.Ordered, E IEnumerable[T]](src E) (def T, _ error) {
e := src()
max, err := e.Next()
if err != nil {
if isEOC(err) {
err = InvalidOperation
}
return def, err
}
for {
v, err := e.Next()
if err != nil {
if isEOC(err) {
return max, nil
}
return def, err
}
if v > max {
max = v
}
}
}
// MaxBy returns the maximum value in a generic sequence according to a specified key selector function.
func MaxBy[T any, K constraints.Ordered, E IEnumerable[T]](src E, keySelector func(T) (K, error)) (def T, _ error) {
e := src()
max, err := e.Next()
if err != nil {
if isEOC(err) {
err = InvalidOperation
}
return def, err
}
maxk, err := keySelector(max)
if err != nil {
return def, err
}
for {
v, err := e.Next()
if err != nil {
if isEOC(err) {
return max, nil
}
return def, err
}
k, err := keySelector(v)
if err != nil {
return def, err
}
if k > maxk {
max, maxk = v, k
}
}
}
// MaxByFunc returns the maximum value in a generic sequence according to a comparer function.
func MaxByFunc[T any, E IEnumerable[T]](src E, greater func(a, b T) (bool, error)) (def T, _ error) {
e := src()
max, err := e.Next()
if err != nil {
if isEOC(err) {
err = InvalidOperation
}
return def, err
}
for {
v, err := e.Next()
if err != nil {
if isEOC(err) {
return max, nil
}
return def, err
}
b, err := greater(v, max)
if err != nil {
return def, err
}
if b {
max = v
}
}
}