-
Notifications
You must be signed in to change notification settings - Fork 11
/
map.go
43 lines (31 loc) · 933 Bytes
/
map.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, and returns an array that contains the results.
func Map[T any, R any](callback func(T) R) func([]T) []R {
return func(xs []T) []R {
result := make([]R, 0, len(xs))
for _, x := range xs {
result = append(result, callback(x))
}
return result
}
}
// See Map but callback receives index of element.
func MapWithIndex[T any, R any](callback func(T, int) R) func([]T) []R {
return func(xs []T) []R {
result := make([]R, 0, len(xs))
for i, x := range xs {
result = append(result, callback(x, i))
}
return result
}
}
// Like Map but callback receives index of element and the whole array.
func MapWithSlice[T any, R any](callback func(T, int, []T) R) func([]T) []R {
return func(xs []T) []R {
result := make([]R, 0, len(xs))
for i, x := range xs {
result = append(result, callback(x, i, xs))
}
return result
}
}