-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathaggregate.go
78 lines (73 loc) · 2.48 KB
/
aggregate.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"
)
// [Aggregate] applies an accumulator function over a sequence.
//
// [Aggregate]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.aggregate
func Aggregate[Source any](source iter.Seq[Source], accumulator func(Source, Source) Source) (Source, error) {
if source == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilSource)
}
if accumulator == nil {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrNilAccumulator)
}
var res Source
empty := true
first := true
for s := range source {
empty = false
if first {
first = false
res = s
continue
}
res = accumulator(res, s)
}
if empty {
return generichelper.ZeroValue[Source](), errorhelper.CallerError(ErrEmptySource)
}
return res, nil
}
// [AggregateSeed] applies an accumulator function over a sequence.
// The specified seed value is used as the initial accumulator value.
//
// [AggregateSeed]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.aggregate
func AggregateSeed[Source, Accumulate any](source iter.Seq[Source],
seed Accumulate, accumulator func(Accumulate, Source) Accumulate) (Accumulate, error) {
if source == nil {
return generichelper.ZeroValue[Accumulate](), errorhelper.CallerError(ErrNilSource)
}
if accumulator == nil {
return generichelper.ZeroValue[Accumulate](), errorhelper.CallerError(ErrNilAccumulator)
}
res := seed
for s := range source {
res = accumulator(res, s)
}
return res, nil
}
// [AggregateSeedSel] applies an accumulator function over a sequence.
// The specified seed value is used as the initial accumulator value,
// and the specified function is used to select the result value.
//
// [AggregateSeedSel]: https://learn.microsoft.com/dotnet/api/system.linq.enumerable.aggregate
func AggregateSeedSel[Source, Accumulate, Result any](source iter.Seq[Source], seed Accumulate,
accumulator func(Accumulate, Source) Accumulate, resultSelector func(Accumulate) Result) (Result, error) {
if source == nil {
return generichelper.ZeroValue[Result](), errorhelper.CallerError(ErrNilSource)
}
if accumulator == nil {
return generichelper.ZeroValue[Result](), errorhelper.CallerError(ErrNilAccumulator)
}
if resultSelector == nil {
return generichelper.ZeroValue[Result](), errorhelper.CallerError(ErrNilSelector)
}
res := seed
for s := range source {
res = accumulator(res, s)
}
return resultSelector(res), nil
}