FlatMap function for arrays/slices
How to write a functional FlatMap function in golang using generics
FlatMap applies a function to each element in the input slice and returns a new slice with the results concatenated. The function f takes an element of type A and returns a slice of elements of type B.
func FlatMap[A, B any](input []A, f func(A) []B) []B {
var result []B
for _, v := range input {
result = append(result, f(v)...)
}
return result
}
and this is a unittest for the function:
func TestFlatMap(t *testing.T) {
input := []int{1, 2, 3}
f := func(a int) []int {
return []int{a, a * 2}
}
expected := []int{1, 2, 2, 4, 3, 6}
result := util.FlatMap(input, f)
if !reflect.DeepEqual(expected, result) {
t.Errorf("Expected %v, got %v", expected, result)
}
}