-
Notifications
You must be signed in to change notification settings - Fork 6
/
elementat.go
44 lines (40 loc) · 1.34 KB
/
elementat.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
package go2linq
import (
"errors"
"iter"
"github.com/solsw/errorhelper"
"github.com/solsw/generichelper"
)
// [ElementAt] returns the element at a specified index in a sequence.
//
// [ElementAt]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.elementat
func ElementAt[Source any](source iter.Seq[Source], index int) (Source, error) {
if source == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilSource)
}
if index < 0 {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrIndexOutOfRange)
}
i := 0
for s := range source {
if i == index {
return s, nil
}
i++
}
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrIndexOutOfRange)
}
// [ElementAtOrDefault] returns the element at a specified index in a sequence or a [zero value] if the index is out of range.
//
// [ElementAtOrDefault]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.elementatordefault
// [zero value]: https://go.dev/ref/spec#The_zero_value
func ElementAtOrDefault[Source any](source iter.Seq[Source], index int) (Source, error) {
if source == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilSource)
}
s, err := ElementAt(source, index)
if errors.Is(err, ErrIndexOutOfRange) {
return generichelper.ZeroValue[Source](), nil
}
return s, nil
}