Skip to content

Commit

Permalink
👔 up: maputil - deep get value update logic on not found
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 27, 2023
1 parent e3b3bfd commit 9765d6d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 14 deletions.
11 changes: 8 additions & 3 deletions maputil/get.go
Expand Up @@ -81,17 +81,22 @@ func GetByPathKeys(mp map[string]any, keys []string) (val any, ok bool) {
}
case []map[string]any: // is an any-map slice
if k == Wildcard {
if kl == i+2 {
if kl == i+2 { // * is last key
return tData, true
}

sl := make([]any, 0, len(tData))
// * is not last key, find sub item data
sl := make([]any, 0)
for _, v := range tData {
if val, ok = GetByPathKeys(v, keys[i+2:]); ok {
sl = append(sl, val)
}
}
return sl, true

if len(sl) > 0 {
return sl, true
}
return nil, false
}

// k is index number
Expand Down
36 changes: 25 additions & 11 deletions maputil/get_test.go
@@ -1,6 +1,7 @@
package maputil_test

import (
"reflect"
"testing"

"github.com/gookit/goutil/dump"
Expand Down Expand Up @@ -94,11 +95,11 @@ var mlMp = map[string]any{
},
"cpt": []map[string]any{
{
"code": "001",
"encounter_uid": "2",
"work_item_uid": "3",
"billing_provider": "Test provider 001",
"resident_provider": "Test Resident Provider",
"code": "001",
"encounter_uid": "2",
"work_item_uid": "3",
"billing_provider": "Test provider 001",
// "resident_provider": "Test Resident Provider",
},
{
"code": "OBS01",
Expand All @@ -108,11 +109,11 @@ var mlMp = map[string]any{
"resident_provider": "Test Resident Provider",
},
{
"code": "SU002",
"encounter_uid": "5",
"work_item_uid": "6",
"billing_provider": "Test provider SU002",
"resident_provider": "Test Resident Provider",
"code": "SU002",
"encounter_uid": "5",
"work_item_uid": "6",
"billing_provider": "Test provider SU002",
// "resident_provider": "Test Resident Provider",
},
},
},
Expand All @@ -137,14 +138,27 @@ func TestGetByPath_deepPath(t *testing.T) {
val, ok = maputil.GetByPath("coding.*.details.em.code", mlMp)
dump.P(ok, val)
assert.True(t, ok)
assert.IsType(t, []any{}, val)

val, ok = maputil.GetByPath("coding.*.details.cpt.*.encounter_uid", mlMp)
dump.P(ok, val)
assert.True(t, ok)
assert.Len(t, val, 1)
assert.IsType(t, []any{}, val)

val, ok = maputil.GetByPath("coding.*.details.cpt.*.work_item_uid", mlMp)
dump.P(ok, val)
// dump.P(ok, val)
assert.True(t, ok)
assert.IsType(t, []any{}, val)

val, ok = maputil.GetByPath("coding.*.details.cpt.*.resident_provider", mlMp)
// dump.P(ok, val)
assert.True(t, ok)
assert.IsKind(t, reflect.Slice, val)

val, ok = maputil.GetByPath("coding.*.details.cpt.*.not-exists", mlMp)
assert.Nil(t, val)
assert.False(t, ok)
}

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

0 comments on commit 9765d6d

Please sign in to comment.