1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-10 07:42:27 +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
}