Skip to content

Commit 401492b

Browse files
committed
Add .ToChannel for iterator method chaining
1 parent 05433c1 commit 401492b

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

iter/iter.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,3 +133,9 @@ func (iter *BaseIter[T]) Filter(fun func(T) bool) *FilterIter[T] {
133133
func (iter *BaseIter[T]) Chain(iterators ...Iterator[T]) *ChainIter[T] {
134134
return Chain[T](append([]Iterator[T]{iter}, iterators...)...)
135135
}
136+
137+
// ToChannel is a convenience method for [ToChannel], providing this iterator
138+
// as an argument.
139+
func (iter *BaseIter[T]) ToChannel() chan T {
140+
return ToChannel[T](iter)
141+
}

iter/iter_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,17 @@ func ExampleToChannel() {
6262
// 3
6363
}
6464

65+
func ExampleToChannel_method() {
66+
for number := range iter.Lift([]int{1, 2, 3}).ToChannel() {
67+
fmt.Println(number)
68+
}
69+
70+
// Output:
71+
// 1
72+
// 2
73+
// 3
74+
}
75+
6576
func ExampleFind() {
6677
values := iter.Lift([]string{"foo", "bar", "baz"})
6778
bar := iter.Find[string](values, func(v string) bool { return v == "bar" })
@@ -190,3 +201,11 @@ func TestBaseIteratorChain(t *testing.T) {
190201
numbers := iter.Lift([]int{1, 2}).Chain(iter.Lift([]int{3, 4})).Collect()
191202
assert.SliceEqual[int](t, numbers, []int{1, 2, 3, 4})
192203
}
204+
205+
func TestBaseIteratorToChannel(t *testing.T) {
206+
expected := 0
207+
for number := range iter.Lift([]int{1, 2, 3, 4}).ToChannel() {
208+
expected += 1
209+
assert.Equal(t, number, expected)
210+
}
211+
}

0 commit comments

Comments
 (0)