This repository has been archived by the owner on Aug 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ordered_iter.go
74 lines (60 loc) · 1.6 KB
/
ordered_iter.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
package iter
import (
"github.com/barweiss/go-tuple"
"golang.org/x/exp/constraints"
)
// Min returns the minimum value in the provided iterator.
func Min[T constraints.Ordered](oi Iter[T]) (T, bool) {
return oi.Reduce(func(curr T, next T) T {
if curr < next {
return curr
}
return next
})
}
// MinByKey returns the value with the minimum result after the application of
// the provided function.
func MinByKey[T any, U constraints.Ordered](i Iter[T], key func(T) U) (T, bool) {
init, ok := i()
if !ok {
var z T
return z, false
}
return Fold(i, tuple.New2(init, key(init)), func(curr tuple.T2[T, U], next T) tuple.T2[T, U] {
keyNext := key(next)
if curr.V2 < keyNext {
return curr
}
return tuple.New2(next, keyNext)
}).V1, true
}
// Max returns the maximum value in the provided iterator.
func Max[T constraints.Ordered](oi Iter[T]) (T, bool) {
return oi.Reduce(func(curr T, next T) T {
if curr > next {
return curr
}
return next
})
}
// MaxByKey returns the value with the maximum result after the application of
// the provided function.
func MaxByKey[T any, U constraints.Ordered](i Iter[T], key func(T) U) (T, bool) {
init, ok := i()
if !ok {
var z T
return z, false
}
return Fold(i, tuple.New2(init, key(init)), func(curr tuple.T2[T, U], next T) tuple.T2[T, U] {
keyNext := key(next)
if curr.V2 > keyNext {
return curr
}
return tuple.New2(next, keyNext)
}).V1, true
}
// Sum returns the sum of all the values in the provided iterator.
func Sum[T constraints.Ordered](oi Iter[T]) T {
var z T
return oi.Fold(z, func(curr, next T) T { return curr + next })
}