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