first commit
This commit is contained in:
26
pkg/tools/list.go
Normal file
26
pkg/tools/list.go
Normal file
@ -0,0 +1,26 @@
|
||||
package tools
|
||||
|
||||
func ListToMap[K comparable, S any](list []S, keyFunc func(S) K) map[K]S {
|
||||
if len(list) == 0 {
|
||||
return make(map[K]S)
|
||||
}
|
||||
result := make(map[K]S, len(list))
|
||||
for _, item := range list {
|
||||
key := keyFunc(item)
|
||||
result[key] = item
|
||||
}
|
||||
return result
|
||||
}
|
||||
func SliceToMapList[K comparable, V any](slice []V, keyFunc func(V) K) map[K][]V {
|
||||
result := make(map[K][]V)
|
||||
for _, v := range slice {
|
||||
key := keyFunc(v)
|
||||
if _, ok := result[key]; !ok {
|
||||
result[key] = make([]V, 0)
|
||||
result[key] = append(result[key], v)
|
||||
} else {
|
||||
result[key] = append(result[key], v)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user