-
Notifications
You must be signed in to change notification settings - Fork 1
/
where.go
54 lines (49 loc) · 1.28 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
package flinx
func Where[T any](predicates ...func(T) bool) func(q Query[T]) Query[T] {
//predicateIdx := func(_ int, item T) bool {
// return predicate(item)
//}
//return WhereIndexed(predicateIdx)
predicate := Predicates(predicates...)
return func(q Query[T]) Query[T] {
return Query[T]{
Iterate: func() Iterator[T] {
next := q.Iterate()
return func() (item T, ok bool) {
for item, ok = next(); ok; item, ok = next() {
if predicate(item) {
return
}
}
return
}
},
}
}
}
// WhereIndexed filters a collection of values based on a predicate. Each
// element's index is used in the logic of the predicate function.
//
// The first argument represents the zero-based index of the element within
// collection. The second argument of predicate represents the element to test.
func WhereIndexed[T any](predicates ...func(int, T) bool) func(q Query[T]) Query[T] {
predicate := PredicatesIndexed(predicates...)
return func(q Query[T]) Query[T] {
return Query[T]{
Iterate: func() Iterator[T] {
next := q.Iterate()
index := 0
return func() (item T, ok bool) {
for item, ok = next(); ok; item, ok = next() {
if predicate(index, item) {
index++
return
}
index++
}
return
}
},
}
}
}