-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfirst.go
78 lines (72 loc) · 2.57 KB
/
first.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
package go2linq
import (
"iter"
"github.com/solsw/errorhelper"
"github.com/solsw/generichelper"
)
// [First] returns the first element of a sequence.
//
// [First]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.first
func First[Source any](source iter.Seq[Source]) (Source, error) {
if source == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilSource)
}
for s := range source {
return s, nil
}
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrEmptySource)
}
// [FirstPred] returns the first element in a sequence that satisfies a specified condition.
//
// [FirstPred]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.first
func FirstPred[Source any](source iter.Seq[Source], predicate func(Source) bool) (Source, error) {
if source == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilSource)
}
if predicate == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilPredicate)
}
empty := true
for s := range source {
empty = false
if predicate(s) {
return s, nil
}
}
if empty {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrEmptySource)
}
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNoMatch)
}
// [FirstOrDefault] returns the first element of a sequence, or a [zero value] if the sequence contains no elements.
//
// [FirstOrDefault]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.firstordefault
// [zero value]: https://go.dev/ref/spec#The_zero_value
func FirstOrDefault[Source any](source iter.Seq[Source]) (Source, error) {
if source == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilSource)
}
r, err := First(source)
if err != nil {
return generichelper.ZeroValue[Source](), nil
}
return r, nil
}
// [FirstOrDefaultPred] returns the first element of the sequence that satisfies a condition
// or a [zero value] if no such element is found.
//
// [FirstOrDefaultPred]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.firstordefault
// [zero value]: https://go.dev/ref/spec#The_zero_value
func FirstOrDefaultPred[Source any](source iter.Seq[Source], predicate func(Source) bool) (Source, error) {
if source == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilSource)
}
if predicate == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilPredicate)
}
r, err := FirstPred(source, predicate)
if err != nil {
return generichelper.ZeroValue[Source](), nil
}
return r, nil
}