-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter.go
More file actions
62 lines (57 loc) · 1.51 KB
/
Copy pathfilter.go
File metadata and controls
62 lines (57 loc) · 1.51 KB
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
package iterator
// Filter returns a modifier that constantly progresses the iterator to the next item
// matching pred
func Filter[T any](pred func(int, T) (bool, error)) Modifier[T, T] {
return FilterMap(func(i int, item T) (T, bool, error) {
matches, err := pred(i, item)
if err != nil {
return *new(T), false, err
}
if !matches {
return *new(T), false, err
}
return item, matches, nil
})
}
// RemoveFunc returns a modifier that filters away items matching fn
func RemoveFunc[T any](fn func(int, T) (bool, error)) Modifier[T, T] {
return Filter(func(i int, item T) (bool, error) {
rem, err := fn(i, item)
if err != nil {
return false, err
}
return !rem, nil
})
}
// Remove returns a modifier that filters away items equal to rem
func Remove[T comparable](rem T) Modifier[T, T] {
return RemoveFunc(func(_ int, item T) (bool, error) {
if item == rem {
return true, nil
}
return false, nil
})
}
func DistinctFunc[T any, S comparable](fn func(int, T) (S, error)) Modifier[T, T] {
return func(iter Iterator[T]) Iterator[T] {
set := make(map[S]struct{})
return RemoveFunc(func(i int, item T) (bool, error) {
key, err := fn(i, item)
if err != nil {
return false, err
}
_, ok := set[key]
if ok {
return true, nil
}
set[key] = struct{}{}
return false, nil
})(iter)
}
}
// Distinct is a modifier that skips duplicate items
func Distinct[T comparable](iter Iterator[T]) Iterator[T] {
return DistinctFunc(func(_ int, item T) (T, error) {
return item, nil
})(iter)
}