-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
iter.go
74 lines (66 loc) · 1.36 KB
/
iter.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//go:build go1.23
package linq
import (
"context"
"iter"
)
// All returns an iterator function
func (e Enumerable[T]) All() iter.Seq2[T, error] {
return func(yield func(T, error) bool) {
er := e()
for {
v, err := er.Next()
if err != nil {
if isEOC(err) {
return
}
yield(v, err)
return
}
if !yield(v, nil) {
return
}
}
}
}
// All returns an iterator function
func (e OrderedEnumerable[T]) All() iter.Seq2[T, error] {
return func(yield func(T, error) bool) {
er := e()
for {
v, err := er.Next()
if err != nil {
if isEOC(err) {
return
}
yield(v, err)
return
}
if !yield(v, nil) {
return
}
}
}
}
// FromIterator generates an IEnumerable[T] from an iterator function.
func FromIterator[T any](ctx context.Context, it iter.Seq[T]) Enumerable[T] {
return Generator(ctx, func(yield func(T) error) error {
for v := range it {
if err := yield(v); err != nil {
return err
}
}
return nil
})
}
// FromIterator2 generates an IEnumerable[KeyValue[K,V]] from an iterator function.
func FromIterator2[K comparable, V any](ctx context.Context, it iter.Seq2[K, V]) Enumerable[KeyValue[K, V]] {
return Generator(ctx, func(yield func(KeyValue[K, V]) error) error {
for k, v := range it {
if err := yield(KeyValue[K, V]{k, v}); err != nil {
return err
}
}
return nil
})
}