-
Notifications
You must be signed in to change notification settings - Fork 4
/
flatmap.go
49 lines (44 loc) · 1.49 KB
/
flatmap.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 hoff
import "context"
// FlatMap applies a transformation to an array of elements and
// returns another array with the transformed result.
func FlatMap[In, Out any](arr []In, fn func(In) []Out) (out []Out) {
for _, elem := range arr {
out = append(out, fn(elem)...)
}
return out
}
// FlatMapError applies a transformation to an array of elements and
// returns another array with the transformed result. If one of the
// transformations fails, it will return early.
func FlatMapError[In, Out any](arr []In, fn func(In) ([]Out, error)) (out []Out, err error) {
for _, elem := range arr {
tr, err := fn(elem)
if err != nil {
return nil, err
}
out = append(out, tr...)
}
return out, nil
}
// FlatMapContext applies the FlatMap transformation while, at the same time,
// shares a context with the transforming function.
func FlatMapContext[In, Out any](ctx context.Context, arr []In, fn func(context.Context, In) []Out) (out []Out) {
for _, elem := range arr {
out = append(out, fn(ctx, elem)...)
}
return out
}
// FlatMapContextError applies the FlatMap transformation while, at the same time,
// shares a context with the transforming function. If one of the
// transformations fails, it will return early.
func FlatMapContextError[In, Out any](ctx context.Context, arr []In, fn func(context.Context, In) ([]Out, error)) (out []Out, err error) {
for _, elem := range arr {
tr, err := fn(ctx, elem)
if err != nil {
return nil, err
}
out = append(out, tr...)
}
return out, nil
}