-
Notifications
You must be signed in to change notification settings - Fork 0
/
contains.go
48 lines (45 loc) · 1.28 KB
/
contains.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
package iterator
// ContainsFunc calls fn on each item in the given iterator.
// It stops as soon as fn returns true and reports that.
func ContainsFunc[T any](iter Iterator[T], fn func(int, T) (bool, error)) (bool, error) {
result := false
if _, err := Iterate(iter, func(i int, item T) (bool, error) {
contains, err := fn(i, item)
if err != nil {
return false, err
}
if contains {
result = true
}
return !contains, nil
}); err != nil {
return false, err
}
return result, nil
}
// ContainsAny returns true as soon as it encounters any of the given values in the given iterator.
func ContainsAny[T comparable](iter Iterator[T], values ...T) (bool, error) {
return ContainsFunc(iter, func(_ int, item T) (bool, error) {
for _, value := range values {
if item == value {
return true, nil
}
}
return false, nil
})
}
// ContainsAll returns true when it has encountered all the given values in the given iterator.
func ContainsAll[T comparable](iter Iterator[T], values ...T) (bool, error) {
return ContainsFunc(iter, func(_ int, item T) (bool, error) {
for i, value := range values {
if item == value {
if len(values) == 1 {
return true, nil
}
values = append(values[:i], values[i+1:]...)
return false, nil
}
}
return false, nil
})
}