Reduce function for arrays/slices
How to write a functional Reduce function in golang using generics
Reduce applies a binary function to each element in the input slice and an accumulator, returning the final value of the accumulator. The function f takes an accumulator of type B and an element of type A and returns a new accumulator of type B.
func Reduce[A any, B any](input []A, initial B, f func(B, A) B) B {
accumulator := initial
for _, v := range input {
accumulator = f(accumulator, v)
}
return accumulator
}
and this is a unittest for the function:
func TestReduce(t *testing.T) {
input := []int{1, 2, 3, 4, 5}
initial := 0
f := func(b int, a int) int {
return b + a
}
expected := 15
result := util.Reduce(input, initial, f)
if expected != result {
t.Errorf("Expected %v, got %v", expected, result)
}
}