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:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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"})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user