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