From 401492b88653fa77b256393383c2d51c9a816a31 Mon Sep 17 00:00:00 2001 From: Tom Godkin Date: Thu, 24 Aug 2023 16:55:49 +0100 Subject: [PATCH] Add .ToChannel for iterator method chaining --- iter/iter.go | 6 ++++++ iter/iter_test.go | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/iter/iter.go b/iter/iter.go index ccf8f78..c7de3f4 100644 --- a/iter/iter.go +++ b/iter/iter.go @@ -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) +} diff --git a/iter/iter_test.go b/iter/iter_test.go index 30affe1..86009a0 100644 --- a/iter/iter_test.go +++ b/iter/iter_test.go @@ -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" }) @@ -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) + } +}