Skip to content

Commit

Permalink
Add .ToChannel for iterator method chaining
Browse files Browse the repository at this point in the history
  • Loading branch information
BooleanCat committed Aug 24, 2023
1 parent 05433c1 commit 401492b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions iter/iter.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,9 @@ func (iter *BaseIter[T]) Filter(fun func(T) bool) *FilterIter[T] {
func (iter *BaseIter[T]) Chain(iterators ...Iterator[T]) *ChainIter[T] {
return Chain[T](append([]Iterator[T]{iter}, iterators...)...)
}

// ToChannel is a convenience method for [ToChannel], providing this iterator
// as an argument.
func (iter *BaseIter[T]) ToChannel() chan T {
return ToChannel[T](iter)
}
19 changes: 19 additions & 0 deletions iter/iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ func ExampleToChannel() {
// 3
}

func ExampleToChannel_method() {
for number := range iter.Lift([]int{1, 2, 3}).ToChannel() {
fmt.Println(number)
}

// Output:
// 1
// 2
// 3
}

func ExampleFind() {
values := iter.Lift([]string{"foo", "bar", "baz"})
bar := iter.Find[string](values, func(v string) bool { return v == "bar" })
Expand Down Expand Up @@ -190,3 +201,11 @@ func TestBaseIteratorChain(t *testing.T) {
numbers := iter.Lift([]int{1, 2}).Chain(iter.Lift([]int{3, 4})).Collect()
assert.SliceEqual[int](t, numbers, []int{1, 2, 3, 4})
}

func TestBaseIteratorToChannel(t *testing.T) {
expected := 0
for number := range iter.Lift([]int{1, 2, 3, 4}).ToChannel() {
expected += 1
assert.Equal(t, number, expected)
}
}

0 comments on commit 401492b

Please sign in to comment.