-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuncs_filtering.go
46 lines (41 loc) · 1.13 KB
/
funcs_filtering.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
package handy
import (
"github.com/hsldymq/goiter"
"iter"
)
func filter[T any](e Iterable[T], predicate func(T) bool) Enumerable[T] {
return NewEnumerator(goiter.Filter(e.Iter(), predicate))
}
func distinct[T any](e Enumerable[T]) Enumerable[T] {
typeComparable := isTypeComparable[T]()
_, comparableImpl := any(zVal[T]()).(Comparable)
if comparableImpl {
return distinctBy(e, func(v T) any { return any(v).(Comparable).ComparingKey() })
} else if typeComparable {
return distinctBy(e, func(v T) any { return v })
} else {
return e
}
}
func distinctBy[T any](e Iterable[T], keySelector func(v T) any) Enumerable[T] {
seq := func(yield func(T) bool) {
yielded := map[any]bool{}
next, stop := iter.Pull(e.Iter())
defer stop()
for {
v, ok := next()
if !ok {
return
}
k := keySelector(v)
if yielded[k] {
continue
}
yielded[k] = true
if !yield(v) {
return
}
}
}
return NewEnumerator(seq)
}