-
Notifications
You must be signed in to change notification settings - Fork 6
/
take.go
96 lines (90 loc) · 2.39 KB
/
take.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
package go2linq
import (
"iter"
"slices"
"github.com/solsw/errorhelper"
)
// [Take] returns a specified number of contiguous elements from the start of a sequence.
//
// [Take]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.take
func Take[Source any](source iter.Seq[Source], count int) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if count <= 0 {
return Empty[Source](), nil
}
return func(yield func(Source) bool) {
i := 0
for s := range source {
if !yield(s) {
return
}
i++
if i >= count {
return
}
}
},
nil
}
// [TakeLast] returns a new [iter.Seq] that contains the last 'count' elements from 'source'.
//
// [TakeLast]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.takelast
func TakeLast[Source any](source iter.Seq[Source], count int) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if count <= 0 {
return Empty[Source](), nil
}
sl := slices.Collect(source)
return slices.Values(sl[len(sl)-count:]), nil
}
// [TakeWhile] returns elements from a sequence as long as a specified condition is true.
//
// [TakeWhile]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.takewhile
func TakeWhile[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) {
for s := range source {
if !predicate(s) {
return
}
if !yield(s) {
return
}
}
},
nil
}
// [TakeWhileIdx] returns elements from a sequence as long as a specified condition is true.
// The element's index is used in the logic of the predicate function.
//
// [TakeWhileIdx]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.takewhile
func TakeWhileIdx[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) {
i := 0
for s := range source {
if !predicate(s, i) {
return
}
if !yield(s) {
return
}
i++
}
},
nil
}