Skip to content

Commit 291888d

Browse files
Rajan-226BooleanCat
authored andcommitted
Add iter.ForEach
1 parent 66f7313 commit 291888d

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

iter/iter.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,14 @@ func ToChannel[T any](iter Iterator[T]) chan T {
6060

6161
return ch
6262
}
63+
64+
// ForEach consumes an iterator and executes callback function on each item.
65+
func ForEach[T any](iter Iterator[T], callback func(T)) {
66+
for {
67+
if value, ok := iter.Next().Value(); ok {
68+
callback(value)
69+
} else {
70+
break
71+
}
72+
}
73+
}

iter/iter_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,22 @@ func TestToChannelEmpty(t *testing.T) {
7070
t.Fail()
7171
}
7272
}
73+
74+
func TestForEach(t *testing.T) {
75+
words := iter.Lift([]string{"foo", "bar", "baz"})
76+
sum := ""
77+
iter.ForEach[string](words, func(word string) {
78+
sum += word
79+
})
80+
assert.Equal(t, "foobarbaz", sum)
81+
}
82+
83+
func TestForEachEmpty(t *testing.T) {
84+
words := iter.Lift([]string{})
85+
sum := ""
86+
iter.ForEach[string](words, func(word string) {
87+
sum += word
88+
})
89+
90+
assert.Empty[string](t, sum)
91+
}

0 commit comments

Comments
 (0)