UniqueBy function for arrays/slices
How to write a functional UniqueBy function in golang using generics
UniqueBy applies a function to each element in the input slice and returns a new slice containing the unique elements based on the function's return value. The function f takes an element of type A and returns a key of type K.
func UniqueBy[A any, K comparable](input []A, f func(A) K) []A {
seen := make(map[K]bool)
var result []A
for _, v := range input {
key := f(v)
if !seen[key] {
seen[key] = true
result = append(result, v)
}
}
return result
}
and this is a unittest for the function:
func TestUniqueBy(t *testing.T) {
input := []string{"apple", "banana", "cherry", "date", "elderberry"}
f := func(a string) int {
return len(a)
}
expected := []string{"apple", "banana", "date", "elderberry"}
result := util.UniqueBy(input, f)
if !reflect.DeepEqual(expected, result) {
t.Errorf("Expected %v, got %v", expected, result)
}
}