This commit is contained in:
xing 2023-01-12 12:54:14 +08:00
parent c9fe47da2f
commit 8c59a9fdac
2 changed files with 97 additions and 0 deletions

View File

@ -24,3 +24,23 @@ func GetStrMapAnyVal[T any](key string, v map[string]any) (r T, o bool) {
}
return
}
func GetStrMapAnyValToAny(key string, v map[string]any) (r any, o bool) {
k := strings.Split(key, ".")
if len(k) > 1 {
val, ok := v[k[0]]
if ok {
vx, ok := val.(map[string]any)
if ok {
r, o = GetStrMapAnyValToAny(strings.Join(k[1:], "."), vx)
}
}
} else {
x, ok := v[k[0]]
if ok {
o = true
r = x
}
}
return
}

View File

@ -33,6 +33,24 @@ func TestGetStrMapAnyVal(t *testing.T) {
},
},
}, wantR: 10, wantO: true},
{name: "t3", args: args{
key: "k2.vv",
v: map[string]any{
"k1": 1,
"k2": map[string]any{
"kk": 10,
},
},
}, wantR: 0, wantO: false},
{name: "t4", args: args{
key: "k3",
v: map[string]any{
"k1": 1,
"k2": map[string]any{
"kk": 10,
},
},
}, wantR: 0, wantO: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@ -46,3 +64,62 @@ func TestGetStrMapAnyVal(t *testing.T) {
})
}
}
func TestGetStrMapAnyValToAny(t *testing.T) {
type args struct {
key string
v map[string]any
}
tests := []struct {
name string
args args
wantR any
wantO bool
}{
{name: "t1", args: args{
key: "k1",
v: map[string]any{
"k1": 1,
"k2": 2,
},
}, wantR: any(1), wantO: true},
{name: "t2", args: args{
key: "k2.kk",
v: map[string]any{
"k1": 1,
"k2": map[string]any{
"kk": 10,
},
},
}, wantR: any(10), wantO: true},
{name: "t3", args: args{
key: "k2.vv",
v: map[string]any{
"k1": 1,
"k2": map[string]any{
"kk": 10,
},
},
}, wantR: nil, wantO: false},
{name: "t4", args: args{
key: "k3",
v: map[string]any{
"k1": 1,
"k2": map[string]any{
"kk": 10,
},
},
}, wantR: nil, wantO: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotR, gotO := GetStrMapAnyValToAny(tt.args.key, tt.args.v)
if !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("GetStrMapAnyValToAny() gotR = %v, want %v", gotR, tt.wantR)
}
if gotO != tt.wantO {
t.Errorf("GetStrMapAnyValToAny() gotO = %v, want %v", gotO, tt.wantO)
}
})
}
}