Skip to content

Commit

Permalink
FEATURE: When calling Set() with key pointing to nonexistent map path…
Browse files Browse the repository at this point in the history
…, the path will be created. (#66)
  • Loading branch information
geseq authored and hanzei committed Apr 26, 2018
1 parent 8a3f715 commit 2b6f327
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions accessors.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
curMSI[thisSel] = value
return nil
}

_, ok := curMSI[thisSel].(map[string]interface{})
if (curMSI[thisSel] == nil || !ok) && index == -1 && isSet {
curMSI[thisSel] = map[string]interface{}{}
}

current = curMSI[thisSel]
default:
current = nil
Expand Down
17 changes: 17 additions & 0 deletions accessors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,23 @@ func TestAccessorsAccessSetDeepDeep(t *testing.T) {
assert.Equal(t, 5, m.Get("one.two.three.four").Data())
}

func TestAccessorsAccessSetDeepDeepWithoutExisting(t *testing.T) {
m := objx.Map{}

m.Set("one.two.three.four", 5)
m.Set("one.two.three.five", 6)

assert.Equal(t, 5, m.Get("one.two.three.four").Data())
assert.Equal(t, 6, m.Get("one.two.three.five").Data())

m.Set("one.two", 7)
assert.Equal(t, 7, m.Get("one.two").Data())
assert.Equal(t, nil, m.Get("one.two.three.four").Data())

m.Set("one.two.three", 8)
assert.Equal(t, 8, m.Get("one.two.three").Data())
}

func TestAccessorsAccessSetArray(t *testing.T) {
m := objx.Map{
"names": []interface{}{"Tyler"},
Expand Down

0 comments on commit 2b6f327

Please sign in to comment.