Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions coderd/util/slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ func Overlap[T comparable](a []T, b []T) bool {
})
}

// Unique returns a new slice with all duplicate elements removed.
// This is a slow function on large lists.
// TODO: Sort elements and implement a faster search algorithm if we
// really start to use this.
func Unique[T comparable](a []T) []T {
cpy := make([]T, 0, len(a))
for _, v := range a {
v := v
if !Contains(cpy, v) {
cpy = append(cpy, v)
}
}
return cpy
}

func OverlapCompare[T any](a []T, b []T, equal func(a, b T) bool) bool {
// For each element in b, if at least 1 is contained in 'a',
// return true.
Expand Down
16 changes: 16 additions & 0 deletions coderd/util/slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,22 @@ import (
"github.com/coder/coder/coderd/util/slice"
)

func TestUnique(t *testing.T) {
t.Parallel()

require.ElementsMatch(t,
[]int{1, 2, 3, 4, 5},
slice.Unique([]int{
1, 2, 3, 4, 5, 1, 2, 3, 4, 5,
}))

require.ElementsMatch(t,
[]string{"a"},
slice.Unique([]string{
"a", "a", "a",
}))
}

func TestContains(t *testing.T) {
t.Parallel()

Expand Down
Loading