From 879238cda106eebe473e85b57f7c75f1224c764a Mon Sep 17 00:00:00 2001 From: xing Date: Wed, 28 Jun 2023 22:49:45 +0800 Subject: [PATCH] map RecursiveSetStrVal --- helper/maps/function.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/helper/maps/function.go b/helper/maps/function.go index 3589550..a00fa82 100644 --- a/helper/maps/function.go +++ b/helper/maps/function.go @@ -106,3 +106,30 @@ func GetAnyAnyValWithDefaults[T any](m map[any]any, defaults T, key ...any) (r T r = v return } + +func RecursiveSetStrVal[T any](m map[string]any, k string, v T) { + kk := strings.Split(k, ".") + if len(kk) < 1 { + return + } else if len(kk) < 2 { + m[k] = v + return + } + for i, _ := range kk[0 : len(kk)-1] { + key := strings.Join(kk[0:i+1], ".") + mm, ok := GetStrAnyVal[map[string]any](m, key) + if !ok { + mm = map[string]any{} + preKey := strings.Join(kk[0:i], ".") + if preKey == "" { + RecursiveSetStrVal(m, key, mm) + } else { + m, _ := GetStrAnyVal[map[string]any](m, preKey) + RecursiveSetStrVal(m, kk[i], mm) + } + } + } + key := strings.Join(kk[0:len(kk)-1], ".") + mm, _ := GetStrAnyVal[map[string]any](m, key) + mm[kk[len(kk)-1]] = v +}