-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathskip.go
107 lines (101 loc) · 2.66 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package go2linq
import (
"iter"
"slices"
"github.com/solsw/errorhelper"
)
// [Skip] bypasses a specified number of elements in a sequence and then returns the remaining elements.
//
// [Skip]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.skip
func Skip[Source any](source iter.Seq[Source], count int) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if count <= 0 {
return source, nil
}
return func(yield func(Source) bool) {
i := 0
for s := range source {
if i < count {
i++
continue
}
if !yield(s) {
return
}
}
},
nil
}
// [SkipLast] returns a new sequence that contains the elements from 'source'
// with the last 'count' elements of the source collection omitted.
//
// [SkipLast]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.skiplast
func SkipLast[Source any](source iter.Seq[Source], count int) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if count <= 0 {
return source, nil
}
ss := slices.Collect(source)
return slices.Values(ss[:len(ss)-count]), nil
}
// [SkipWhile] bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
//
// [SkipWhile]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.skipwhile
func SkipWhile[Source any](source iter.Seq[Source], predicate func(Source) bool) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if predicate == nil {
return nil, errorhelper.CallerError(ErrNilPredicate)
}
return func(yield func(Source) bool) {
rest := false
for s := range source {
if !rest {
if predicate(s) {
continue
} else {
rest = true
}
}
if !yield(s) {
return
}
}
},
nil
}
// [SkipWhileIdx] bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.
// The element's index is used in the logic of the predicate function.
//
// [SkipWhileIdx]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.skipwhile
func SkipWhileIdx[Source any](source iter.Seq[Source], predicate func(Source, int) bool) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if predicate == nil {
return nil, errorhelper.CallerError(ErrNilPredicate)
}
return func(yield func(Source) bool) {
rest := false
i := 0
for s := range source {
if !rest {
if predicate(s, i) {
i++
continue
} else {
rest = true
}
}
if !yield(s) {
return
}
}
},
nil
}