refactor patch function

This commit is contained in:
filifa 2024-07-11 20:16:32 -05:00
parent d96c3f5d84
commit babc02905d
1 changed files with 41 additions and 37 deletions

View File

@ -36,23 +36,17 @@ type about struct {
CaptivatingIndex json.Number CaptivatingIndex json.Number
} }
func patch(obj any, path string, value any) error { func setValue(obj any, key string, value any) error {
if string(path[0]) == "/" {
path = path[1:]
}
var err error var err error
first, rest, found := strings.Cut(path, "/")
if !found {
switch v := obj.(type) { switch v := obj.(type) {
case *FeedResponse: case *FeedResponse:
log.Println("Formerly %v", (*v)[first]) log.Println("Formerly %v", (*v)[key])
(*v)[first] = value (*v)[key] = value
case map[string]any: case map[string]any:
log.Println("Formerly %v", v[first]) log.Println("Formerly %v", v[key])
v[first] = value v[key] = value
case []any: case []any:
idx, err := strconv.Atoi(first) idx, err := strconv.Atoi(key)
if err != nil { if err != nil {
break break
} }
@ -72,6 +66,23 @@ func patch(obj any, path string, value any) error {
return err return err
} }
func expand(v []any, idx int) {
if len(v) <= idx {
arr := make([]any, idx+1)
for i, val := range v {
arr[i] = val
}
v = arr
}
}
func patch(obj any, path string, value any) error {
var err error
first, rest, found := strings.Cut(path, "/")
if !found {
setValue(obj, first, value)
}
switch v := obj.(type) { switch v := obj.(type) {
case *FeedResponse: case *FeedResponse:
err = patch((*v)[first], rest, value) err = patch((*v)[first], rest, value)
@ -83,14 +94,7 @@ func patch(obj any, path string, value any) error {
break break
} }
if len(v) <= idx { expand(v, idx)
arr := make([]any, idx+1)
for i, val := range v {
arr[i] = val
}
v = arr
}
err = patch(v[idx], rest, value) err = patch(v[idx], rest, value)
default: default:
err = errors.New("couldn't determine type") err = errors.New("couldn't determine type")