Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SliceFindDuplicates function #15

Merged
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
20 changes: 20 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,23 @@ func SliceMapFunc[S ~[]E, E any](s S, f func(E, int) E) S {
}
return r
}

// SliceFindDuplicates takes a slice of comparable elements and returns a new slice containing
// only the elements that appear more than once in the input slice. Since a map is used
// internally to track duplicates, the order of the elements in the output slice is not guaranteed.
func SliceFindDuplicates[S ~[]E, E comparable](s S) S {
elementCount := make(map[E]int)
duplicates := []E{}

for _, element := range s {
elementCount[element]++
}

for element, count := range elementCount {
if count > 1 {
duplicates = append(duplicates, element)
}
}

return duplicates
}
10 changes: 10 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,13 @@ func (s *SliceFuncs) TestSliceMapFunc() {
return strings.TrimSpace(v)
}), "SliceMapFunc should return {\"a\", \"b\", \"c\"}")
}

func (s *SliceFuncs) TestSliceFindDuplicates() {
a := []string{"foo", "bar", "bar", "foo", "roll", "roll"}
b := []string{"apple", "book", "clock", "duck", "escape", "field"}
c := []string{"foo", "bar", "roll", "roll", "desk"}

require.ElementsMatch(s.T(), []string{"foo", "bar", "roll"}, SliceFindDuplicates(a), "SliceFindDuplicates should return elements: {foo, bar, roll}")
require.ElementsMatch(s.T(), []string{}, SliceFindDuplicates(b), "SliceFindDuplicates should return elements: {}")
require.ElementsMatch(s.T(), []string{"roll"}, SliceFindDuplicates(c), "SliceFindDuplicates should return elements: {roll}")
}
Loading