Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
Comment thread
lucarin91 marked this conversation as resolved.

import "iter"

// FilterIter takes an iterator and a matcher and returns only those elements that satisfy the matcher.
Comment thread
lucarin91 marked this conversation as resolved.
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.
Comment thread
lucarin91 marked this conversation as resolved.
Outdated
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.
Comment thread
lucarin91 marked this conversation as resolved.
Outdated
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
}
14 changes: 14 additions & 0 deletions slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
package f

import (
"iter"
"runtime"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -124,3 +125,16 @@ func Count[T any](in []T, matcher Matcher[T]) int {
}
return count
}

// RefIter takes a slice of type []T and returns an iterator that yields
// pointers to each element of the slice.
func RefIter[T any](slice []T) iter.Seq[*T] {
return func(yield func(*T) bool) {
for i := range slice {
if !yield(&slice[i]) {
return
}
}
}
}