-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.go
73 lines (54 loc) · 1.62 KB
/
filter.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package stream
import "sync"
type FilterAction[T any] func(T) bool
// Filter returns a stream consisting of the elements of this stream that match
// the given action.
func (p *BaseStream[T]) Filter(action FilterAction[T]) *BaseStream[T] {
p.C = Filter(p.C, action)
return p
}
// Filter returns a channel consisting of the elements of input channel that match
// the given action.
func Filter[T any](input <-chan T, action FilterAction[T]) chan T {
output := make(chan T)
go filter(input, output, action)
return output
}
// Filter returns a stream consisting of the elements of this stream that match
// the given action, parallel.
func (p *ParallelStream[T]) Filter(action FilterAction[T]) *ParallelStream[T] {
p.C = FilterParallel(p.C, p.Size, action)
return p
}
// FilterParallel returns a channel consisting of the elements of input channel that match
// the given action, parallel.
func FilterParallel[T any](input <-chan T, size int, action FilterAction[T]) chan T {
output := make(chan T)
group := &sync.WaitGroup{}
group.Add(size)
for i := 0; i < size; i++ {
go filterParallel(input, output, group, action)
}
go waitAndClose(output, group)
return output
}
func filter[T any](input <-chan T, output chan<- T, action FilterAction[T]) {
for elem := range input {
if action(elem) {
output <- elem
}
}
close(output)
}
func filterParallel[T any](input <-chan T, output chan<- T, group *sync.WaitGroup, action FilterAction[T]) {
for elem := range input {
if action(elem) {
output <- elem
}
}
group.Done()
}
func waitAndClose[T any](output chan<- T, group *sync.WaitGroup) {
group.Wait()
close(output)
}