-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmin.go
87 lines (83 loc) · 1.58 KB
/
min.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"
// Min returns the minimum value in a sequence of values.
func Min[T constraints.Ordered, E IEnumerable[T]](src E) (def T, _ error) {
e := src()
min, 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 min, nil
}
return def, err
}
if v < min {
min = v
}
}
}
// MinBy returns the minimum value in a generic sequence according to a specified key selector function.
func MinBy[T any, K constraints.Ordered, E IEnumerable[T]](src E, keySelector func(T) (K, error)) (def T, _ error) {
e := src()
min, err := e.Next()
if err != nil {
if isEOC(err) {
err = InvalidOperation
}
return def, err
}
mink, err := keySelector(min)
if err != nil {
return def, err
}
for {
v, err := e.Next()
if err != nil {
if isEOC(err) {
return min, nil
}
return def, err
}
k, err := keySelector(v)
if err != nil {
return def, err
}
if k < mink {
min, mink = v, k
}
}
}
// MinByFunc returns the minimum value in a generic sequence according to a comparer function.
func MinByFunc[T any, E IEnumerable[T]](src E, less func(a, b T) (bool, error)) (def T, _ error) {
e := src()
min, 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 min, nil
}
return def, err
}
b, err := less(v, min)
if err != nil {
return def, err
}
if b {
min = v
}
}
}