From afb344a1b1bad6068f492665e77b4796df15efd5 Mon Sep 17 00:00:00 2001 From: lucarin91 Date: Mon, 19 Jan 2026 16:00:15 +0100 Subject: [PATCH] feat: add iterator support --- go.mod | 2 +- iter.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 iter.go diff --git a/go.mod b/go.mod index 37ff180..6ea1593 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module go.bug.st/f -go 1.22.3 +go 1.25 require github.com/stretchr/testify v1.9.0 diff --git a/iter.go b/iter.go new file mode 100644 index 0000000..a94fb4b --- /dev/null +++ b/iter.go @@ -0,0 +1,41 @@ +package f + +import "iter" + +// FilterIter takes an iterator and a matcher and returns only those elements that satisfy the matcher. +func FilterIter[T any](values iter.Seq[T], matcher Matcher[T]) iter.Seq[T] { + return func(yield func(x T) bool) { + for x := range values { + if matcher(x) { + if !yield(x) { + return + } + } + } + } +} + +// Map applies the Mapper function to each element of the iterator. +func MapIter[T, U any](values iter.Seq[T], mapper Mapper[T, U]) iter.Seq[U] { + return func(yield func(x U) bool) { + for x := range values { + if !yield(mapper(x)) { + return + } + } + } +} + +// Reducer is a function that reduces an iterator's elements to a single value. +func ReduceIter[T any](values iter.Seq[T], reducer Reducer[T], initialValue ...T) T { + var result T + if len(initialValue) > 1 { + panic("initialValue must be a single value") + } else if len(initialValue) == 1 { + result = initialValue[0] + } + for v := range values { + result = reducer(result, v) + } + return result +}