Skip to content

Commit

Permalink
feat: filter channel
Browse files Browse the repository at this point in the history
  • Loading branch information
katallaxie authored Oct 25, 2024
1 parent 1362921 commit 079a597
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
16 changes: 16 additions & 0 deletions channels/channels.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
22 changes: 22 additions & 0 deletions channels/channels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 079a597

Please sign in to comment.