-
Notifications
You must be signed in to change notification settings - Fork 6
/
defaultifempty.go
49 lines (45 loc) · 1.35 KB
/
defaultifempty.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"
"github.com/solsw/generichelper"
)
// [DefaultIfEmpty] returns the elements of a specified sequence
// or the type parameter's [zero value] in a singleton collection if the sequence is empty.
//
// [DefaultIfEmpty]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.defaultifempty
// [zero value]: https://go.dev/ref/spec#The_zero_value
func DefaultIfEmpty[Source any](source iter.Seq[Source]) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
r, err := DefaultIfEmptyDef(source, generichelper.ZeroValue[Source]())
if err != nil {
return nil, errorhelper.CallerError(err)
}
return r, nil
}
// [DefaultIfEmptyDef] returns the elements of a specified sequence
// or a specified value in a singleton collection if the sequence is empty.
//
// [DefaultIfEmptyDef]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.defaultifempty
func DefaultIfEmptyDef[Source any](source iter.Seq[Source], defaultValue Source) (iter.Seq[Source], error) {
if source == nil {
return nil, errorhelper.CallerError(ErrNilSource)
}
return func(yield func(Source) bool) {
empty := true
for s := range source {
empty = false
if !yield(s) {
return
}
}
if empty {
if !yield(defaultValue) {
return
}
}
},
nil
}