mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
unique function
This commit is contained in:
parent
f6af583408
commit
2882dc1f9f
3 changed files with 49 additions and 0 deletions
21
docs/content/collections/unique.md
Normal file
21
docs/content/collections/unique.md
Normal 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
12
unique.go
Normal 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
16
unique_test.go
Normal 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))
|
||||
}
|
||||
Loading…
Reference in a new issue