1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-06 13:42:28 +08:00

feat: add KeyBy for slice

This commit is contained in:
dudaodong
2022-11-05 16:52:31 +08:00
parent 8c036f830c
commit 260fb795d3
2 changed files with 22 additions and 0 deletions

View File

@@ -833,3 +833,15 @@ func AppendIfAbsent[T comparable](slice []T, value T) []T {
}
return slice
}
// KeyBy converts a slice to a map based on a callback function
func KeyBy[T any, U comparable](slice []T, iteratee func(T) U) map[U]T {
result := make(map[U]T, len(slice))
for _, v := range slice {
k := iteratee(v)
result[k] = v
}
return result
}

View File

@@ -644,3 +644,13 @@ func TestReplaceAll(t *testing.T) {
assert.Equal([]string{"x", "b", "x", "c", "d", "x"}, ReplaceAll(strs, "a", "x"))
assert.Equal([]string{"a", "b", "a", "c", "d", "a"}, ReplaceAll(strs, "e", "x"))
}
func TestKeyBy(t *testing.T) {
assert := internal.NewAssert(t, "TestKeyBy")
result := KeyBy([]string{"a", "ab", "abc"}, func(str string) int {
return len(str)
})
assert.Equal(result, map[int]string{1: "a", 2: "ab", 3: "abc"})
}