-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
skip.go
93 lines (83 loc) · 1.96 KB
/
skip.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package linq
type skipEnumerator[T any] struct {
src Enumerator[T]
cnt int
}
// Skip bypasses a specified number of elements in a sequence and then returns the remaining elements.
func Skip[T any, E IEnumerable[T]](src E, count int) Enumerable[T] {
return func() Enumerator[T] {
return &skipEnumerator[T]{src: src(), cnt: count}
}
}
func (e *skipEnumerator[T]) Next() (def T, _ error) {
for ; e.cnt > 0; e.cnt-- {
_, err := e.src.Next()
if err != nil {
return def, err
}
}
return e.src.Next()
}
type skipWhileEnumerator[T any] struct {
src Enumerator[T]
pred func(T) (bool, error)
skipped bool
}
// SkipWhile bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
func SkipWhile[T any, E IEnumerable[T]](src E, pred func(T) (bool, error)) Enumerable[T] {
return func() Enumerator[T] {
return &skipWhileEnumerator[T]{src: src(), pred: pred}
}
}
func (e *skipWhileEnumerator[T]) Next() (def T, _ error) {
if e.skipped {
return e.src.Next()
}
for {
v, err := e.src.Next()
if err != nil {
return def, err
}
ok, err := e.pred(v)
if err != nil {
return def, err
}
if !ok {
e.skipped = true
return v, nil
}
}
}
type skipLastEnumerator[T any] struct {
src Enumerator[T]
cnt int
buf []T
i int
}
// SkipLast returns a new enumerable collection that contains the elements from source with the last count elements of the source collection omitted.
func SkipLast[T any, E IEnumerable[T]](src E, count int) Enumerable[T] {
return func() Enumerator[T] {
return &skipLastEnumerator[T]{src: src(), cnt: count}
}
}
func (e *skipLastEnumerator[T]) Next() (def T, _ error) {
if e.buf == nil {
e.buf = make([]T, e.cnt)
for i := 0; i < e.cnt; i++ {
v, err := e.src.Next()
if err != nil {
return def, err
}
e.buf[i] = v
}
}
i := e.i % e.cnt
r := e.buf[i]
v, err := e.src.Next()
if err != nil {
return def, err
}
e.buf[i] = v
e.i++
return r, nil
}