-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinq.go
65 lines (54 loc) · 970 Bytes
/
linq.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
package linq
import (
"iter"
"slices"
)
type query[T any] iter.Seq[T]
func New[T any](iterator iter.Seq[T]) query[T] {
return query[T](iterator)
}
func (f query[T]) ToIter() iter.Seq[T] {
return iter.Seq[T](f)
}
func (f query[T]) ToSlice() []T {
l := make([]T, 0)
for v := range f {
l = append(l, v)
}
return l
}
func (f query[T]) Where(cond func(x T) bool) query[T] {
return func(yield func(x T) bool) {
for v := range f {
if !cond(v) {
continue
}
if !yield(v) {
return
}
}
}
}
func (f query[T]) OrderBy(cmp func(a, b T) int) query[T] {
values := make([]T, 0)
for v := range f {
values = append(values, v)
}
slices.SortFunc(values, cmp)
return func(yield func(T) bool) {
for _, v := range values {
if !yield(v) {
return
}
}
}
}
func (f query[T]) Select(selector func(item T) T) query[T] {
return func(yield func(T) bool) {
for v := range f {
if !(yield(selector(v))) {
return
}
}
}
}