-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfilter.go
49 lines (37 loc) · 922 Bytes
/
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
package fp
// Returns the elements of an array that meet the condition specified in a callback function.
func Filter[T any](predicate func(T) bool) func([]T) []T {
return func(xs []T) []T {
result := []T{}
for _, x := range xs {
if predicate(x) {
result = append(result, x)
}
}
return result
}
}
// See Filter but callback receives index of element.
func FilterWithIndex[T any](predicate func(T, int) bool) func([]T) []T {
return func(xs []T) []T {
result := []T{}
for i, x := range xs {
if predicate(x, i) {
result = append(result, x)
}
}
return result
}
}
// Like Filter but callback receives index of element and the whole array.
func FilterWithSlice[T any](predicate func(T, int, []T) bool) func([]T) []T {
return func(xs []T) []T {
result := []T{}
for i, x := range xs {
if predicate(x, i, xs) {
result = append(result, x)
}
}
return result
}
}