Skip to content

Commit

Permalink
feat: map - add new func Flatten, FlatWithFunc for
Browse files Browse the repository at this point in the history
flat tree map
  • Loading branch information
inhere committed Sep 5, 2022
1 parent d21b1a9 commit ee252cd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
14 changes: 11 additions & 3 deletions maputil/convert.go
Expand Up @@ -88,16 +88,24 @@ func FormatIndent(mp any, indent string) string {
// ->
// {"top.sub": "value", "top.sub2": "value2" }
func Flatten(mp map[string]any) map[string]interface{} {
// TODO convert
return mp
if mp == nil {
return nil
}

flatMp := make(map[string]any, len(mp))
flatMap(reflect.ValueOf(mp), "", func(path string, val reflect.Value) {
flatMp[path] = val.Interface()
})

return flatMp
}

// FlatFunc custom collect handle func
type FlatFunc func(path string, val reflect.Value)

// FlatWithFunc flat a tree-map with custom collect handle func
func FlatWithFunc(mp map[string]any, fn FlatFunc) {
if mp == nil {
if mp == nil || fn == nil {
return
}

Expand Down
29 changes: 23 additions & 6 deletions maputil/convert_test.go
Expand Up @@ -18,15 +18,15 @@ func TestKeyToLower(t *testing.T) {
}

func TestToStringMap(t *testing.T) {
src := map[string]interface{}{"a": "v0", "b": 23}
src := map[string]any{"a": "v0", "b": 23}
ret := maputil.ToStringMap(src)

assert.Eq(t, ret["a"], "v0")
assert.Eq(t, ret["b"], "23")
}

func TestHttpQueryString(t *testing.T) {
src := map[string]interface{}{"a": "v0", "b": 23}
src := map[string]any{"a": "v0", "b": 23}
str := maputil.HttpQueryString(src)

fmt.Println(str)
Expand All @@ -35,15 +35,15 @@ func TestHttpQueryString(t *testing.T) {
}

func TestToString2(t *testing.T) {
src := map[string]interface{}{"a": "v0", "b": 23}
src := map[string]any{"a": "v0", "b": 23}

s := maputil.ToString2(src)
assert.Contains(t, s, "b:23")
assert.Contains(t, s, "a:v0")
}

func TestToString(t *testing.T) {
src := map[string]interface{}{"a": "v0", "b": 23}
src := map[string]any{"a": "v0", "b": 23}

s := maputil.ToString(src)
dump.P(s)
Expand All @@ -53,9 +53,26 @@ func TestToString(t *testing.T) {
s = maputil.ToString(nil)
assert.Eq(t, "", s)

s = maputil.ToString(map[string]interface{}{})
s = maputil.ToString(map[string]any{})
assert.Eq(t, "{}", s)

s = maputil.ToString(map[string]interface{}{"": nil})
s = maputil.ToString(map[string]any{"": nil})
assert.Eq(t, "{:}", s)
}

func TestFlatten(t *testing.T) {
data := map[string]any{
"name": "inhere",
"age": 234,
"top": map[string]any{
"sub0": "val0",
"sub1": []string{"val1-0", "val1-1"},
},
}

mp := maputil.Flatten(data)
assert.ContainsKeys(t, mp, []string{"age", "name", "top.sub0", "top.sub1[0]", "top.sub1[1]"})
assert.Nil(t, maputil.Flatten(nil))

maputil.FlatWithFunc(nil, nil)
}

0 comments on commit ee252cd

Please sign in to comment.