From 079a597be475bc637be599ea14bebc223fd7b8ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20D=C3=B6ll?= Date: Fri, 25 Oct 2024 20:00:16 +0000 Subject: [PATCH] feat: filter channel --- channels/channels.go | 16 ++++++++++++++++ channels/channels_test.go | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+) 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) +}