-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloop.go
47 lines (41 loc) · 865 Bytes
/
loop.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package iterable
// LoopIterator is a different form of iterator better suited for use in for-loops:
//
// for it := iterable.Start(x); it.HasNext(); it.Next() {
// doSomethingWith(it.Current())
// }
//
type LoopIterator[T any] struct {
it Iterator[T]
current T
ok bool
}
func Start[T any](i Iterable[T]) LoopIterator[T] {
it := i.Iterator()
v, ok := it.Next()
return LoopIterator[T]{
it: it,
current: v,
ok: ok,
}
}
func (l *LoopIterator[T]) HasNext() bool {
return l.ok
}
func (l *LoopIterator[T]) Next() {
l.current, l.ok = l.it.Next()
}
func (l *LoopIterator[T]) Current() T {
return l.current
}
// Foreach runs the function f on each element of the iterable.
func Foreach[T any](i Iterable[T], f func(elem T)) {
it := i.Iterator()
for {
elem, ok := it.Next()
if !ok {
return
}
f(elem)
}
}