Skip to content

Commit

Permalink
👔 up: maputil - update SimpleMerge() support deep merge map[string]any
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 16, 2023
1 parent 57af4da commit a3c2084
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
10 changes: 8 additions & 2 deletions maputil/maputil.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,19 @@ func SimpleMerge(src, dst map[string]any) map[string]any {
if len(src) == 0 {
return dst
}

if len(dst) == 0 {
return src
}

for key, val := range src {
if mp, ok := val.(map[string]any); ok {
if dmp, ok := dst[key].(map[string]any); ok {
dst[key] = SimpleMerge(mp, dmp)
continue
}
}

// simple merge
dst[key] = val
}
return dst
Expand All @@ -54,7 +61,6 @@ func MergeStringMap(src, dst map[string]string, ignoreCase bool) map[string]stri
if ignoreCase {
k = strings.ToLower(k)
}

dst[k] = v
}
return dst
Expand Down
19 changes: 19 additions & 0 deletions maputil/maputil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,19 @@ func TestSimpleMerge(t *testing.T) {

ret = maputil.SimpleMerge(src, nil)
assert.Eq(t, "v0", ret["A"])

src = map[string]any{"A": "v0", "B": "v1", "sub": map[string]any{"s1": "sv0"}}
dst = map[string]any{"A": "v1", "B": "v2", "sub": map[string]any{
"s1": "sv1",
"s2": "sv2",
}}
ret = maputil.SimpleMerge(src, dst)

dm := maputil.Data(ret)
assert.Eq(t, "v0", dm.Str("A"))
assert.Eq(t, "v1", dm.Str("B"))
assert.Eq(t, "sv0", dm.Str("sub.s1"))
assert.Eq(t, "sv2", dm.Str("sub.s2"))
}

func TestMergeStringMap(t *testing.T) {
Expand All @@ -30,6 +43,12 @@ func TestMergeStringMap(t *testing.T) {

ret = maputil.MergeSMap(map[string]string{"A": "v0"}, map[string]string{"a": "v1"}, true)
assert.Eq(t, map[string]string{"a": "v0"}, ret)

ret = maputil.MergeSMap(map[string]string{"A": "v0"}, nil, false)
assert.Eq(t, map[string]string{"A": "v0"}, ret)

ret = maputil.MergeSMap(nil, map[string]string{"a": "v1"}, true)
assert.Eq(t, map[string]string{"a": "v1"}, ret)
}

func TestMakeByPath(t *testing.T) {
Expand Down

0 comments on commit a3c2084

Please sign in to comment.