refactor patch function
This commit is contained in:
parent
d96c3f5d84
commit
babc02905d
|
@ -36,40 +36,51 @@ type about struct {
|
|||
CaptivatingIndex json.Number
|
||||
}
|
||||
|
||||
func patch(obj any, path string, value any) error {
|
||||
if string(path[0]) == "/" {
|
||||
path = path[1:]
|
||||
func setValue(obj any, key string, value any) error {
|
||||
var err error
|
||||
switch v := obj.(type) {
|
||||
case *FeedResponse:
|
||||
log.Println("Formerly %v", (*v)[key])
|
||||
(*v)[key] = value
|
||||
case map[string]any:
|
||||
log.Println("Formerly %v", v[key])
|
||||
v[key] = value
|
||||
case []any:
|
||||
idx, err := strconv.Atoi(key)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
if len(v) <= idx {
|
||||
arr := make([]any, idx+1)
|
||||
for i, val := range v {
|
||||
arr[i] = val
|
||||
}
|
||||
v = arr
|
||||
}
|
||||
v[idx] = value
|
||||
default:
|
||||
err = errors.New("couldn't determine type")
|
||||
}
|
||||
|
||||
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 {
|
||||
switch v := obj.(type) {
|
||||
case *FeedResponse:
|
||||
log.Println("Formerly %v", (*v)[first])
|
||||
(*v)[first] = value
|
||||
case map[string]any:
|
||||
log.Println("Formerly %v", v[first])
|
||||
v[first] = value
|
||||
case []any:
|
||||
idx, err := strconv.Atoi(first)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
if len(v) <= idx {
|
||||
arr := make([]any, idx+1)
|
||||
for i, val := range v {
|
||||
arr[i] = val
|
||||
}
|
||||
v = arr
|
||||
}
|
||||
v[idx] = value
|
||||
default:
|
||||
err = errors.New("couldn't determine type")
|
||||
}
|
||||
|
||||
return err
|
||||
setValue(obj, first, value)
|
||||
}
|
||||
|
||||
switch v := obj.(type) {
|
||||
|
@ -83,14 +94,7 @@ func patch(obj any, path string, value any) error {
|
|||
break
|
||||
}
|
||||
|
||||
if len(v) <= idx {
|
||||
arr := make([]any, idx+1)
|
||||
for i, val := range v {
|
||||
arr[i] = val
|
||||
}
|
||||
v = arr
|
||||
}
|
||||
|
||||
expand(v, idx)
|
||||
err = patch(v[idx], rest, value)
|
||||
default:
|
||||
err = errors.New("couldn't determine type")
|
||||
|
|
Loading…
Reference in New Issue