diff --git a/iterator/operation.go b/iterator/operation.go index f0f2e65..a2ec362 100644 --- a/iterator/operation.go +++ b/iterator/operation.go @@ -101,3 +101,14 @@ func (iter *joinIterator[T]) HasNext() bool { return result } + +// Reduce reduces iter to a single value using the reduction function reducer +func Reduce[T any, U any](iter Iterator[T], initial U, reducer func(U, T) U) U { + acc := initial + + for item, ok := iter.Next(); ok; item, ok = iter.Next() { + acc = reducer(acc, item) + } + + return acc +} diff --git a/iterator/operation_test.go b/iterator/operation_test.go index 89cd529..71e184a 100644 --- a/iterator/operation_test.go +++ b/iterator/operation_test.go @@ -52,3 +52,11 @@ func TestJoinIterator(t *testing.T) { assert.Equal([]int{2, 3, 4}, ToSlice(iter)) } + +func TestReduce(t *testing.T) { + assert := internal.NewAssert(t, "TestReduce") + + iter := FromSlice([]int{1, 2, 3, 4}) + sum := Reduce(iter, 0, func(a, b int) int { return a + b }) + assert.Equal(10, sum) +}