Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module go.bug.st/f

go 1.22.3
go 1.25

require github.com/stretchr/testify v1.9.0

Expand Down
41 changes: 41 additions & 0 deletions iter.go
Original file line number Diff line number Diff line change
@@ -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
}