Skip to content

Commit 54826a9

Browse files
committed
slices: add slices.Unique
1 parent 48b10c9 commit 54826a9

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/slices/slices.go

+12
Original file line numberDiff line numberDiff line change
@@ -474,3 +474,15 @@ func Concat[S ~[]E, E any](slices ...S) S {
474474
}
475475
return newslice
476476
}
477+
478+
// Unique replaces runs of equal elements with a single copy.
479+
// Unique modifies the contents of the slice s and returns the modified slice,
480+
// which may have a smaller length.
481+
func Unique[S ~[]E, E comparable](s S) S {
482+
for i := len(s) - 1; i > 0; i-- {
483+
if Index(s, s[i]) != i {
484+
s = Delete(s, i, i+1)
485+
}
486+
}
487+
return s
488+
}

src/slices/slices_test.go

+46
Original file line numberDiff line numberDiff line change
@@ -1335,3 +1335,49 @@ func TestConcat_too_large(t *testing.T) {
13351335
}
13361336
}
13371337
}
1338+
1339+
var uniqueTests = []struct {
1340+
name string
1341+
s []int
1342+
want []int
1343+
}{
1344+
{
1345+
"nil",
1346+
nil,
1347+
nil,
1348+
},
1349+
{
1350+
"one",
1351+
[]int{1},
1352+
[]int{1},
1353+
},
1354+
{
1355+
"sorted",
1356+
[]int{1, 2, 3},
1357+
[]int{1, 2, 3},
1358+
},
1359+
{
1360+
"1 item",
1361+
[]int{1, 1, 2},
1362+
[]int{1, 2},
1363+
},
1364+
{
1365+
"unsorted",
1366+
[]int{1, 2, 1},
1367+
[]int{1, 2},
1368+
},
1369+
{
1370+
"many",
1371+
[]int{1, 2, 2, 3, 3, 4},
1372+
[]int{1, 2, 3, 4},
1373+
},
1374+
}
1375+
1376+
func TestUnique(t *testing.T) {
1377+
for _, test := range uniqueTests {
1378+
sliceCopy := Clone(test.s)
1379+
if got := Unique(sliceCopy); !Equal(got, test.want) {
1380+
t.Errorf("Unique(%v) = %v, want %v", test.s, got, test.want)
1381+
}
1382+
}
1383+
}

0 commit comments

Comments
 (0)