wp-go/helper/maps/map.go

58 lines
1.0 KiB
Go
Raw Normal View History

2023-01-21 11:31:23 +00:00
package maps
2023-01-14 13:12:26 +00:00
import "encoding/json"
2023-01-17 15:18:31 +00:00
func StrAnyMapToStruct[T any, M any](m M) (r T, err error) {
2023-01-14 13:12:26 +00:00
str, err := json.Marshal(m)
if err != nil {
return
}
err = json.Unmarshal(str, &r)
return
}
2023-01-17 15:18:31 +00:00
func StructToAnyMap[K comparable, T any](s T) (r map[K]any, err error) {
2023-01-14 13:12:26 +00:00
marshal, err := json.Marshal(s)
if err != nil {
return
}
2023-01-17 15:18:31 +00:00
r = make(map[K]any)
2023-01-14 13:12:26 +00:00
err = json.Unmarshal(marshal, &r)
return
}
2023-01-21 11:31:23 +00:00
func FilterToSlice[T any, K comparable, V any](m map[K]V, fn func(K, V) (T, bool)) (r []T) {
2023-01-14 13:12:26 +00:00
for k, v := range m {
vv, ok := fn(k, v)
if ok {
r = append(r, vv)
}
}
return
}
2023-01-21 11:31:23 +00:00
// AnyAnyToStrAny map[any]any => map[string]any 方便json转换
func AnyAnyToStrAny(m map[any]any) (r map[string]any) {
r = make(map[string]any)
for k, v := range m {
kk, ok := k.(string)
if ok {
vv, ok := v.(map[any]any)
if ok {
2023-01-21 11:31:23 +00:00
r[kk] = AnyAnyToStrAny(vv)
} else {
r[kk] = v
}
}
}
return
}
2023-01-25 18:26:36 +00:00
func Reduce[T, V any, K comparable](m map[K]V, fn func(K, V, T) T, r T) T {
for k, v := range m {
r = fn(k, v, r)
}
return r
}