-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathwhere.go
56 lines (52 loc) · 1.29 KB
/
where.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
package go2linq
import (
"iter"
"github.com/solsw/errorhelper"
)
// [Where] filters a sequence of values based on a predicate.
//
// [Where]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.where
func Where[Source any](source iter.Seq[Source], predicate func(Source) bool) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if predicate == nil {
return nil, errorhelper.CallerError(ErrNilPredicate)
}
return func(yield func(Source) bool) {
for s := range source {
if !predicate(s) {
continue
}
if !yield(s) {
return
}
}
},
nil
}
// [WhereIdx] filters a sequence of values based on a predicate.
// Each element's index is used in the logic of the predicate function.
//
// [WhereIdx]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.where
func WhereIdx[Source any](source iter.Seq[Source], predicate func(Source, int) bool) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if predicate == nil {
return nil, errorhelper.CallerError(ErrNilPredicate)
}
return func(yield func(Source) bool) {
i := -1
for s := range source {
i++
if !predicate(s, i) {
continue
}
if !yield(s) {
return
}
}
},
nil
}