Skip to content

Commit df04872

Browse files
committed
Infinite parameter for the Repeat iterator
1 parent 6dca1e2 commit df04872

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

repeat.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,22 @@ func Repeat[T any](value T, n int) Iter[T] {
55
// Initialisation of a new channel.
66
iter := Instance[T](int64(n), false)
77

8+
// If the length is below zero, then
9+
// the iterator will run forever.
10+
if n < 0 {
11+
iter.SetInfinite(true)
12+
}
13+
814
go func() {
915
defer iterRecover()
1016
defer iter.Close()
1117

18+
if iter.IsInfinite() {
19+
for {
20+
iter.Chan() <- value
21+
}
22+
}
23+
1224
for step := 0; step < n; step++ {
1325
iter.Chan() <- value
1426
}

repeat_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,17 @@ func TestRepeat(t *testing.T) {
1212
assert.Exactly(t, []string{"A", "A", "A"}, slice)
1313
}
1414
}
15+
16+
func TestRepeatInfinite(t *testing.T) {
17+
repeat := Repeat("A", -1)
18+
assert.Exactly(t, true, repeat.IsInfinite())
19+
20+
var data []string
21+
for i := 0; i <= 3; i++ {
22+
if next, err := repeat.Next(); assert.Nil(t, err) {
23+
data = append(data, next)
24+
}
25+
}
26+
27+
assert.Exactly(t, []string{"A", "A", "A", "A"}, data)
28+
}

0 commit comments

Comments
 (0)