diff --git a/channels/channels.go b/channels/channels.go index f0f4d1e..d5ad8e2 100644 --- a/channels/channels.go +++ b/channels/channels.go @@ -55,3 +55,19 @@ func Drain[T any](input <-chan T) { } }() } + +// Filter filters the channel with the given function. +func Filter[T any](input <-chan T, fn func(T) bool) <-chan T { + c := make(chan T) + + go func() { + defer close(c) + for v := range input { + if fn(v) { + c <- v + } + } + }() + + return c +} diff --git a/channels/channels_test.go b/channels/channels_test.go index f74fbb8..be051a6 100644 --- a/channels/channels_test.go +++ b/channels/channels_test.go @@ -41,3 +41,25 @@ func TestDrain(t *testing.T) { require.Empty(t, in, 0) } + +func TestFilter(t *testing.T) { + in := make(chan int) + out := Filter(in, func(v int) bool { + return v%2 == 0 + }) + + go func() { + in <- 1 + in <- 2 + in <- 3 + close(in) + }() + + el := []int{} + + for v := range out { + el = append(el, v) + } + + assert.Equal(t, []int{2}, el) +}