unique function

This commit is contained in:
Ruidy 2022-04-12 17:25:45 -04:00
parent f6af583408
commit 2882dc1f9f
3 changed files with 49 additions and 0 deletions

View file

@ -0,0 +1,21 @@
---
title: "Unique"
date: 2022-04-12T17:18:04-04:00
---
`Unique` returns a duplicate-free version of the slice. Only the first occurrence of each value is kept.
```go
package main
import (
"fmt"
u "github.com/rjNemo/underscore"
)
func main() {
nums := []int{1, 4, 2, 5, 3, 1, 5, 2, 8, 9}
fmt.Println(u.Unique(nums)) // 1, 4, 2, 5, 3, 8, 9
}
```

12
unique.go Normal file
View file

@ -0,0 +1,12 @@
package underscore
func Unique[T comparable](values []T) (uniques []T) {
seen := make(map[T]bool, 0)
for _, v := range values {
if _, ok := seen[v]; !ok {
uniques = append(uniques, v)
seen[v] = true
}
}
return uniques
}

16
unique_test.go Normal file
View file

@ -0,0 +1,16 @@
package underscore_test
import (
"testing"
"github.com/stretchr/testify/assert"
u "github.com/rjNemo/underscore"
)
func TestUnique(t *testing.T) {
nums := []int{1, 4, 2, 5, 3, 1, 5, 2, 8, 9}
want := []int{1, 4, 2, 5, 3, 8, 9}
assert.Equal(t, want, u.Unique(nums))
}