Files
mayfly-go/server/pkg/utils/collx/map.go

58 lines
1.2 KiB
Go
Raw Normal View History

package collx
2020-09-01 10:34:11 +08:00
2023-10-20 21:31:46 +08:00
import "mayfly-go/pkg/utils/anyx"
2020-09-01 10:34:11 +08:00
2023-10-12 12:14:56 +08:00
// M is a shortcut for map[string]any
type M map[string]any
2021-04-16 15:10:07 +08:00
2023-10-12 12:14:56 +08:00
// 将偶数个元素转为对应的M (map[string]any)
//
// 偶数索引为key奇数为value
func Kvs(elements ...any) M {
myMap := make(map[string]any)
2021-04-16 15:10:07 +08:00
2023-10-12 12:14:56 +08:00
for i := 0; i < len(elements); i += 2 {
2023-10-20 21:31:46 +08:00
key := anyx.ToString(elements[i])
2023-10-12 12:14:56 +08:00
if i+1 < len(elements) {
value := elements[i+1]
myMap[key] = value
} else {
myMap[key] = nil
}
}
return myMap
2021-04-16 15:10:07 +08:00
}
// Keys returns the keys of the map m.
// The keys will be in an indeterminate order.
func MapKeys[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
// Values returns the values of the map m.
// The values will be in an indeterminate order.
func MapValues[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
// MapMerge maps merge, 若存在重复的key则以最后的map值为准
func MapMerge[M ~map[K]V, K comparable, V any](maps ...M) M {
mergedMap := make(M)
for _, m := range maps {
for k, v := range m {
mergedMap[k] = v
}
}
return mergedMap
}