Unique function for arrays/slices
How to write a functional Unique function in golang using generics
Unique returns a new slice containing the unique elements from the input slice.
func Unique[A comparable](input []A) []A {
seen := make(map[A]bool)
var result []A
for _, v := range input {
if !seen[v] {
seen[v] = true
result = append(result, v)
}
}
return result
}
and this is a unittest for the function:
func TestUnique(t *testing.T) {
input := []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}
expected := []int{1, 2, 3, 4}
result := util.Unique(input)
if !reflect.DeepEqual(expected, result) {
t.Errorf("Expected %v, got %v", expected, result)
}
}