-
Notifications
You must be signed in to change notification settings - Fork 6
/
select.go
49 lines (45 loc) · 1.22 KB
/
select.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
package go2linq
import (
"iter"
"github.com/solsw/errorhelper"
)
// [Select] projects each element of a sequence into a new form.
//
// [Select]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.select
func Select[Source, Result any](source iter.Seq[Source], selector func(Source) Result) (iter.Seq[Result], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if selector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
return func(yield func(Result) bool) {
for s := range source {
if !yield(selector(s)) {
return
}
}
},
nil
}
// [SelectIdx] projects each element of a sequence into a new form by incorporating the element's index.
//
// [SelectIdx]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.select
func SelectIdx[Source, Result any](source iter.Seq[Source], selector func(Source, int) Result) (iter.Seq[Result], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
if selector == nil {
return nil, errorhelper.CallerError(ErrNilSelector)
}
return func(yield func(Result) bool) {
i := 0
for s := range source {
if !yield(selector(s, i)) {
return
}
i++
}
},
nil
}