Skip to content

Commit 85e8b63

Browse files
committed
Remove duplicate types
1 parent daa5eec commit 85e8b63

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

coderd/util/slice/slice.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,22 @@ func Overlap[T comparable](a []T, b []T) bool {
2222
})
2323
}
2424

25+
// Unique returns a new slice with all duplicate elements removed.
26+
// This is a slow function on large lists.
27+
// TODO: Sort elements and implement a faster search algorithm if we
28+
//
29+
// really start to use this.
30+
func Unique[T comparable](a []T) []T {
31+
cpy := make([]T, 0, len(a))
32+
for _, v := range a {
33+
v := v
34+
if !Contains(cpy, v) {
35+
cpy = append(cpy, v)
36+
}
37+
}
38+
return cpy
39+
}
40+
2541
func OverlapCompare[T any](a []T, b []T, equal func(a, b T) bool) bool {
2642
// For each element in b, if at least 1 is contained in 'a',
2743
// return true.

coderd/util/slice/slice_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,22 @@ import (
99
"github.com/coder/coder/coderd/util/slice"
1010
)
1111

12+
func TestUnique(t *testing.T) {
13+
t.Parallel()
14+
15+
require.ElementsMatch(t,
16+
[]int{1, 2, 3, 4, 5},
17+
slice.Unique([]int{
18+
1, 2, 3, 4, 5, 1, 2, 3, 4, 5,
19+
}))
20+
21+
require.ElementsMatch(t,
22+
[]string{"a"},
23+
slice.Unique([]string{
24+
"a", "a", "a",
25+
}))
26+
}
27+
1228
func TestContains(t *testing.T) {
1329
t.Parallel()
1430

scripts/apitypings/main.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import (
1313
"strings"
1414
"text/template"
1515

16+
"github.com/coder/coder/coderd/util/slice"
17+
1618
"github.com/fatih/structtag"
1719
"golang.org/x/tools/go/packages"
1820
"golang.org/x/xerrors"
@@ -316,6 +318,8 @@ func (g *Generator) buildUnion(obj types.Object, st *types.Union) (string, error
316318
allTypes = append(allTypes, "null")
317319
}
318320

321+
allTypes = slice.Unique(allTypes)
322+
319323
s.WriteString(fmt.Sprintf("export type %s = %s\n", obj.Name(), strings.Join(allTypes, " | ")))
320324

321325
return s.String(), nil

0 commit comments

Comments
 (0)