Skip to content
Merged
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
59 changes: 58 additions & 1 deletion it/iter.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package it

import "iter"
import (
"cmp"
"iter"
)

// ForEach consumes an iterator and applies a function to each value yielded.
func ForEach[V any](iter iter.Seq[V], fn func(V)) {
Expand Down Expand Up @@ -39,3 +42,57 @@ func Reduce2[V, W any, R any](iter iter.Seq2[V, W], fn func(R, V, W) R, initial

return result
}

// Max consumes an iterator and returns the maximum value yielded and true if
// there was at least one value, or the zero value and false if the iterator
// was empty.
func Max[V cmp.Ordered](iterator iter.Seq[V]) (V, bool) {
var (
max V
set bool
)

next, _ := iter.Pull(iterator)
first, ok := next()
if !ok {
return max, set
}

max = first
set = true

for item := range iterator {
if item > max {
max = item
}
}

return max, set
}

// Min consumes an iterator and returns the minimum value yielded and true if
// there was at least one value, or the zero value and false if the iterator
// was empty.
func Min[V cmp.Ordered](iterator iter.Seq[V]) (V, bool) {
var (
min V
set bool
)

next, _ := iter.Pull(iterator)
first, ok := next()
if !ok {
return min, set
}

min = first
set = true

for item := range iterator {
if item < min {
min = item
}
}

return min, set
}
30 changes: 30 additions & 0 deletions it/iter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,33 @@ func ExampleReduce2() {

// Output: 3
}

func ExampleMax() {
max, ok := it.Max(slices.Values([]int{1, 2, 3}))
fmt.Println(max, ok)

// Output: 3 true
}

func TestMaxEmpty(t *testing.T) {
t.Parallel()

max, ok := it.Max(it.Exhausted[int]())
assert.Equal(t, max, 0)
assert.False(t, ok)
}

func ExampleMin() {
min, ok := it.Min(slices.Values([]int{4, 2, 1, 3}))
fmt.Println(min, ok)

// Output: 1 true
}

func TestMinEmpty(t *testing.T) {
t.Parallel()

min, ok := it.Min(it.Exhausted[int]())
assert.Equal(t, min, 0)
assert.False(t, ok)
}