Skip to content

Commit 8bb7c4d

Browse files
Add .Filter for iterator method chaining
1 parent 2ef6280 commit 8bb7c4d

File tree

3 files changed

+17
-6
lines changed

3 files changed

+17
-6
lines changed

README.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
A general purpose library offering functional helpers for Golang.
66

77
```go
8-
// Find the first 5 prime numbers
9-
primes := iter.Filter(iter.Count(), isPrime).Take(5).Collect()
10-
reflect.DeepEqual(t, primes, []int{2, 3, 5, 7, 11})
8+
// Find the first 5 even numbers
9+
evens := iter.Count().Filter(filters.IsEven).Take(5).Collect()
10+
reflect.DeepEqual(evens, []int{0, 2, 4, 6, 8})
1111
```
1212

1313
_[Read the docs.](https://pkg.go.dev/github.com/BooleanCat/go-functional)_
@@ -51,9 +51,8 @@ Here are a few trivial example of what's possible using the iterators in this
5151
library.
5252

5353
```go
54-
// All even natural numbers (2, 4, 6, 8...)
55-
isEven := func(n int) bool { return n%2 == 0 }
56-
evens := iter.Filter(iter.Count().Drop(1), isEven)
54+
// All odd natural numbers (1, 3, 5, 7...)
55+
odds := iter.Count().Drop(1).Filter(filters.IsOdd).Collect()
5756
```
5857

5958
```go

iter/iter.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,9 @@ func (iter *BaseIter[T]) Drop(n uint) *DropIter[T] {
121121
func (iter *BaseIter[T]) Take(n uint) *TakeIter[T] {
122122
return Take[T](iter, n)
123123
}
124+
125+
// Filter is a convenience method for [Filter], providing this iterator
126+
// as an argument.
127+
func (iter *BaseIter[T]) Filter(fun func(T) bool) *FilterIter[T] {
128+
return Filter[T](iter, fun)
129+
}

iter/iter_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
"github.com/BooleanCat/go-functional/internal/assert"
99
"github.com/BooleanCat/go-functional/iter"
10+
"github.com/BooleanCat/go-functional/iter/filters"
1011
"github.com/BooleanCat/go-functional/iter/ops"
1112
"github.com/BooleanCat/go-functional/option"
1213
)
@@ -179,3 +180,8 @@ func TestBaseIteratorTake(t *testing.T) {
179180
items := iter.Lift([]int{1, 2, 3}).Take(2).Collect()
180181
assert.SliceEqual(t, items, []int{1, 2})
181182
}
183+
184+
func TestBaseIteratorFilter(t *testing.T) {
185+
items := iter.Lift([]int{1, 2, 3}).Filter(filters.IsEven[int]).Collect()
186+
assert.SliceEqual(t, items, []int{2})
187+
}

0 commit comments

Comments
 (0)