Skip to content

Commit

Permalink
Introduce a new delete function to the map
Browse files Browse the repository at this point in the history
  • Loading branch information
Niels Becker committed Aug 27, 2023
1 parent 1734ff4 commit 377b816
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
9 changes: 9 additions & 0 deletions accessors.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ func (m Map) Has(selector string) bool {
return err == nil
}

// Deletes the value from the element
// Note: Array elements can not be deleted, they will only be set null
// Returns the old element or nil if it did not exist
func (m Map) Delete(selector string) *Value {
val := reflect.ValueOf(nil)
res, _ := access(m, selector, &val, false)
return &Value{data: res}
}

func parsePath(path string) ([]string, error) {
res := make([]string, 0, 8)
path = strings.TrimPrefix(path, ".")
Expand Down
45 changes: 45 additions & 0 deletions accessors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,3 +384,48 @@ func TestGenericDeepNull(t *testing.T) {
assert.Equal(t, `{"nope":null,"null":null}`, json)
}

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

m.Set("other[0].x", "e0")
m.Set("other[1].x", "e1")
m.Set("other[2].x", "e2")

assert.Equal(t, nil, m.Delete("a.b").Data())
assert.Equal(t, "e0", m.Delete("other[0].x").Data())
assert.Equal(t, map[string]interface{}{"x": "e1"}, m.Delete("other[1]").Data())

json, err := m.JSON()
assert.NoError(t, err)
assert.Equal(t, `{"other":[{},null,{"x":"e2"}]}`, json)
}

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

m.Set("other[0].x", "e0")
m.Set("other[1].x", "e1")

assert.Equal(t, "e0", m.Delete("other[0].x").Data())
assert.Equal(t, map[string]interface{}{"x": "e1"}, m.Delete("other[1]").Data())

json, err := m.JSON()
assert.NoError(t, err)
assert.Equal(t, `{"other":[{},null]}`, json)
}

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

m.Set("other[0].x", "e0")
m.Set("other[1].x", "e1")

assert.Equal(t, []interface{}{
map[string]interface{}{"x": "e0"},
map[string]interface{}{"x": "e1"},
}, m.Delete("other").Data())

json, err := m.JSON()
assert.NoError(t, err)
assert.Equal(t, `{}`, json)
}

0 comments on commit 377b816

Please sign in to comment.