File tree 2 files changed +38
-0
lines changed
2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -55,3 +55,19 @@ func Drain[T any](input <-chan T) {
55
55
}
56
56
}()
57
57
}
58
+
59
+ // Filter filters the channel with the given function.
60
+ func Filter [T any ](input <- chan T , fn func (T ) bool ) <- chan T {
61
+ c := make (chan T )
62
+
63
+ go func () {
64
+ defer close (c )
65
+ for v := range input {
66
+ if fn (v ) {
67
+ c <- v
68
+ }
69
+ }
70
+ }()
71
+
72
+ return c
73
+ }
Original file line number Diff line number Diff line change @@ -41,3 +41,25 @@ func TestDrain(t *testing.T) {
41
41
42
42
require .Empty (t , in , 0 )
43
43
}
44
+
45
+ func TestFilter (t * testing.T ) {
46
+ in := make (chan int )
47
+ out := Filter (in , func (v int ) bool {
48
+ return v % 2 == 0
49
+ })
50
+
51
+ go func () {
52
+ in <- 1
53
+ in <- 2
54
+ in <- 3
55
+ close (in )
56
+ }()
57
+
58
+ el := []int {}
59
+
60
+ for v := range out {
61
+ el = append (el , v )
62
+ }
63
+
64
+ assert .Equal (t , []int {2 }, el )
65
+ }
You can’t perform that action at this time.
0 commit comments