-
Notifications
You must be signed in to change notification settings - Fork 4
/
reduce.go
61 lines (56 loc) · 1.3 KB
/
reduce.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
package hoff
import "context"
// Reduce takes an array of input items, runs the callback on each one and accumulates the result.
func Reduce[T, Acc any](
arr []T,
fn func(acc Acc, elem T, index int) Acc,
acc Acc,
) Acc {
for i, elem := range arr {
acc = fn(acc, elem, i)
}
return acc
}
// ReduceContext passes the context arg through to the reducer fn.
func ReduceContext[T, Acc any](
ctx context.Context,
arr []T,
fn func(ctx context.Context, acc Acc, elem T, index int) Acc,
acc Acc,
) Acc {
for i, elem := range arr {
acc = fn(ctx, acc, elem, i)
}
return acc
}
// ReduceError will stop the reducer when an error is encountered and return the Acc and the error encountered.
func ReduceError[T, Acc any](
arr []T,
fn func(acc Acc, elem T, index int) (Acc, error),
acc Acc,
) (Acc, error) {
var err error
for i, elem := range arr {
acc, err = fn(acc, elem, i)
if err != nil {
return acc, err
}
}
return acc, nil
}
// ReduceContextError combines both ReduceContext and ReduceError.
func ReduceContextError[T, Acc any](
ctx context.Context,
arr []T,
fn func(ctx context.Context, acc Acc, elem T, index int) (Acc, error),
acc Acc,
) (Acc, error) {
var err error
for i, elem := range arr {
acc, err = fn(ctx, acc, elem, i)
if err != nil {
return acc, err
}
}
return acc, nil
}