-
Notifications
You must be signed in to change notification settings - Fork 11
/
flatMap.go
43 lines (31 loc) · 974 Bytes
/
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
package fp
// Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.
func FlatMap[T any, R any](callback func(T) []R) func([]T) []R {
return func(xs []T) []R {
result := []R{}
for _, x := range xs {
result = append(result, callback(x)...)
}
return result
}
}
// See FlatMap but callback receives index of element.
func FlatMapWithIndex[T any, R any](callback func(T, int) []R) func([]T) []R {
return func(xs []T) []R {
result := []R{}
for i, x := range xs {
result = append(result, callback(x, i)...)
}
return result
}
}
// Like FlatMap but callback receives index of element and the whole array.
func FlatMapWithSlice[T any, R any](callback func(T, int, []T) []R) func([]T) []R {
return func(xs []T) []R {
result := []R{}
for i, x := range xs {
result = append(result, callback(x, i, xs)...)
}
return result
}
}