feat: sher 包新增 map 相关映射操作

This commit is contained in:
kercylan98 2023-12-29 16:19:49 +08:00
parent 515cbc66eb
commit 7086281399
1 changed files with 25 additions and 0 deletions

25
utils/sher/map.go Normal file
View File

@ -0,0 +1,25 @@
package sher
// MappingFromSlice 将切片中的元素进行转换
func MappingFromSlice[S ~[]V, NS ~[]N, V, N any](slice S, handler func(value V) N) NS {
if slice == nil {
return nil
}
result := make(NS, len(slice))
for i, v := range slice {
result[i] = handler(v)
}
return result
}
// MappingFromMap 将 map 中的元素进行转换
func MappingFromMap[M ~map[K]V, NM ~map[K]N, K comparable, V, N any](m M, handler func(value V) N) NM {
if m == nil {
return nil
}
result := make(NM, len(m))
for k, v := range m {
result[k] = handler(v)
}
return result
}