Skip to content

Commit

Permalink
Showing 2 changed files with 211 additions and 146 deletions.
41 changes: 22 additions & 19 deletions internal/types/document.go
Original file line number Diff line number Diff line change
@@ -321,39 +321,42 @@ func (d *Document) Remove(key string) {

// RemoveByPath removes document by path, doing nothing if the key does not exist.
func (d *Document) RemoveByPath(keys ...string) {
removeByPath(d, keys...)
}

func removeByPath(v any, keys ...string) {
if len(keys) == 0 {
return
}

key := keys[0]
if _, ok := d.m[key]; !ok {
return
}

if len(keys) == 1 {
d.Remove(key)
return
}

key2 := keys[1]
switch x := d.m[key].(type) {
switch v := v.(type) {
case *Document:
d.Remove(key2)
if _, ok := v.m[key]; !ok {
return
}
if len(keys) == 1 {
v.Remove(key)
return
}
removeByPath(v.m[key], keys[1:]...)

case *Array:
i, err := strconv.Atoi(key2)
i, err := strconv.Atoi(key)
if err != nil {
panic("wrong path " + key2)
// return
return // no such path
}
if i > len(v.s)-1 {
return // no such path
}
if i > len(x.s)-1 {
if len(keys) == 1 {
v.s = append(v.s[:i], v.s[i+1:]...)
return
}
x.s = append(x.s[:i], x.s[i+1:]...)
removeByPath(v.s[i], keys[1:]...)
default:
// no path further: scalar value
// no such path: scalar value
}
return
}

// check interfaces
Loading
Oops, something went wrong.

0 comments on commit 285d938

Please sign in to comment.