-
Notifications
You must be signed in to change notification settings - Fork 11
/
reduce.go
37 lines (28 loc) · 914 Bytes
/
reduce.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
package fp
// Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
func Reduce[T any, R any](callback func(R, T) R, acc R) func([]T) R {
return func(xs []T) R {
for _, x := range xs {
acc = callback(acc, x)
}
return acc
}
}
// See Reduce but callback receives index of element.
func ReduceWithIndex[T any, R any](callback func(R, T, int) R, acc R) func([]T) R {
return func(xs []T) R {
for i, x := range xs {
acc = callback(acc, x, i)
}
return acc
}
}
// Like Reduce but callback receives index of element and the whole array.
func ReduceWithSlice[T any, R any](callback func(R, T, int, []T) R, acc R) func([]T) R {
return func(xs []T) R {
for i, x := range xs {
acc = callback(acc, x, i, xs)
}
return acc
}
}