Skip to content

Commit 05433c1

Browse files
committed
Add .Chain for iterator method chaining
1 parent 8bb7c4d commit 05433c1

File tree

4 files changed

+28
-0
lines changed

4 files changed

+28
-0
lines changed

iter/chain_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ func ExampleChain() {
1414
// Output: [1 2 3 4 0 9]
1515
}
1616

17+
func ExampleChain_method() {
18+
fmt.Println(iter.Lift([]int{1, 2}).Chain(iter.Lift([]int{3, 4}), iter.Lift([]int{0, 9})).Collect())
19+
// Output: [1 2 3 4 0 9]
20+
}
21+
1722
func TestChainMultiple(t *testing.T) {
1823
items := iter.Chain[int](iter.Lift([]int{1, 2}), iter.Lift([]int{3, 4}))
1924
assert.Equal(t, items.Next().Unwrap(), 1)

iter/filter_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,18 @@ func ExampleFilter() {
2323
// None
2424
}
2525

26+
func ExampleFilter_method() {
27+
filtered := iter.Lift([]int{0, 1, 0, 2}).Filter(filters.IsZero[int])
28+
fmt.Println(filtered.Next())
29+
fmt.Println(filtered.Next())
30+
fmt.Println(filtered.Next())
31+
32+
// Output:
33+
// Some(0)
34+
// Some(0)
35+
// None
36+
}
37+
2638
func ExampleFilterMap() {
2739
selectAndTripleOdds := func(x int) option.Option[int] {
2840
if x%2 == 0 {

iter/iter.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,9 @@ func (iter *BaseIter[T]) Take(n uint) *TakeIter[T] {
127127
func (iter *BaseIter[T]) Filter(fun func(T) bool) *FilterIter[T] {
128128
return Filter[T](iter, fun)
129129
}
130+
131+
// Chain is a convenience method for [Chain], providing this iterator as an
132+
// argument.
133+
func (iter *BaseIter[T]) Chain(iterators ...Iterator[T]) *ChainIter[T] {
134+
return Chain[T](append([]Iterator[T]{iter}, iterators...)...)
135+
}

iter/iter_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,8 @@ func TestBaseIteratorFilter(t *testing.T) {
185185
items := iter.Lift([]int{1, 2, 3}).Filter(filters.IsEven[int]).Collect()
186186
assert.SliceEqual(t, items, []int{2})
187187
}
188+
189+
func TestBaseIteratorChain(t *testing.T) {
190+
numbers := iter.Lift([]int{1, 2}).Chain(iter.Lift([]int{3, 4})).Collect()
191+
assert.SliceEqual[int](t, numbers, []int{1, 2, 3, 4})
192+
}

0 commit comments

Comments
 (0)