-
Notifications
You must be signed in to change notification settings - Fork 4
/
filter.go
65 lines (60 loc) · 1.53 KB
/
filter.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
package hoff
import "context"
// Filter takes an array of T's and applies the callback fn to each element.
// If fn returns true, the element is included in the returned collection, if false it is excluded.
// Example: [1, 2, 3].Filter(<number is odd?>) = [1, 3].
func Filter[T any](arr []T, fn func(T) bool) (out []T) {
for _, elem := range arr {
if fn(elem) {
out = append(out, elem)
}
}
return out
}
// FilterContext is "context aware" and will pass the parent func's ctx param along to the callback fn.
func FilterContext[T any](
ctx context.Context,
arr []T,
fn func(ctx context.Context, elem T) bool,
) (out []T) {
for _, elem := range arr {
if fn(ctx, elem) {
out = append(out, elem)
}
}
return out
}
// FilterError will return early with the first error encountered in the callback fn, if any.
func FilterError[T any](
arr []T,
fn func(elem T) (bool, error),
) (out []T, err error) {
for _, elem := range arr {
include, err := fn(elem)
if err != nil {
return nil, err
}
if include {
out = append(out, elem)
}
}
return out, nil
}
// FilterContextError combines both "FilterContext" and "FilterError" approaches, passing through the ctx,
// and stopping and returning the first error encountered.
func FilterContextError[T any](
ctx context.Context,
arr []T,
fn func(ctx context.Context, elem T) (bool, error),
) (out []T, err error) {
for _, elem := range arr {
include, err := fn(ctx, elem)
if err != nil {
return nil, err
}
if include {
out = append(out, elem)
}
}
return out, nil
}