1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

fix: fix UniqueBy bug

This commit is contained in:
dudaodong
2024-08-08 10:40:23 +08:00
parent 356351896d
commit 3e7f94b03e
7 changed files with 27 additions and 18 deletions

View File

@@ -783,17 +783,25 @@ func Unique[T comparable](slice []T) []T {
return result
}
// UniqueBy call iteratee func with every item of slice, then remove duplicated.
// Play: https://go.dev/play/p/UR323iZLDpv
func UniqueBy[T comparable](slice []T, iteratee func(item T) T) []T {
result := []T{}
// UniqueBy removes duplicate elements from the input slice based on the values returned by the iteratee function.
// The function maintains the order of the elements.
// Play: todo
func UniqueBy[T any, U comparable](slice []T, iteratee func(item T) U) []T {
result := make([]T, 0, len(slice))
seen := make(map[U]struct{}, len(slice))
for _, v := range slice {
val := iteratee(v)
result = append(result, val)
for i := range slice {
key := iteratee(slice[i])
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
result = append(result, slice[i])
}
return Unique(result)
return result
}
// UniqueByField remove duplicate elements in struct slice by struct field.

View File

@@ -777,7 +777,7 @@ func ExampleUniqueBy() {
fmt.Println(result)
// Output:
// [1 2 0]
// [1 2 3]
}
func ExampleUniqueByField() {

View File

@@ -733,7 +733,8 @@ func TestUniqueBy(t *testing.T) {
actual := UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(val int) int {
return val % 4
})
assert.Equal([]int{1, 2, 3, 0}, actual)
assert.Equal([]int{1, 2, 3, 4}, actual)
}
func TestUniqueByField(t *testing.T) {