Skip to content

Commit

Permalink
deduplicate: zero elements when a slice is shortened
Browse files Browse the repository at this point in the history
  • Loading branch information
mmetc committed Feb 7, 2024
1 parent 612c2ee commit f288261
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
7 changes: 7 additions & 0 deletions slicetools/deduplicate.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,12 @@ func Deduplicate[T comparable](slice []T) []T {
j++
}
}

// Zero elements from j to len(slice), like stdlib methods
var zero T // Default zero value for type T
for i := j; i < len(slice); i++ {
slice[i] = zero
}

return slice[:j]
}
3 changes: 3 additions & 0 deletions slicetools/deduplicate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ func TestUniqueIntegers(t *testing.T) {
if len(got) > 0 {
assert.Equal(t, got, tc.slice[:len(got)], "Deduplicate should modify the original slice!")
}
for i := len(got); i < len(tc.slice); i++ {
assert.Equal(t, 0, tc.slice[i], "Deduplicate should zero out the remaining elements!")
}
})
}
}
Expand Down

0 comments on commit f288261

Please sign in to comment.