Skip to content

Commit fdec8c3

Browse files
committed
add DedupeFunc
1 parent d73b206 commit fdec8c3

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

slice/sliceutil.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,22 @@ func Dedupe[T comparable](inputSlice []T) (result []T) {
3737
return
3838
}
3939

40+
// DedupeFunc removes duplicates from a slice of elements using a key function
41+
// The key function is used to return a key for each element in the slice
42+
// and then the key is used to check for duplicates
43+
func DedupeFunc[T any](inputSlice []T, keyFunc func(T) any) (result []T) {
44+
seen := make(map[any]struct{})
45+
for _, inputValue := range inputSlice {
46+
key := keyFunc(inputValue)
47+
if _, ok := seen[key]; !ok {
48+
seen[key] = struct{}{}
49+
result = append(result, inputValue)
50+
}
51+
}
52+
53+
return
54+
}
55+
4056
// PickRandom item from a slice of elements
4157
func PickRandom[T any](v []T) T {
4258
return v[rand.Intn(len(v))]

0 commit comments

Comments
 (0)