Apply Patch Operations
Hard · Algorithms
Write applyPatch(doc, ops) that applies JSON-Patch-like operations in order. Paths look like "/user/tags/0": every part after a / is an object key or an array index, and the last part is the target inside its parent.
The parent (everything before the last part) must exist and be an object or array, otherwise the operation fails. Then:
- add: on an object, set the key (create or overwrite). On an array, the last part is an index from 0 to length (insert there) or "-" (append).
- remove: the key must exist / the index must be from 0 to length - 1. Removes it (arrays shift left).
- replace: like remove followed by add at the same path; the target must exist.
- move: remove the value at from (must exist), then add it at path.
The patch is atomic: if operation i fails, return { ok: false, failedAt: i }. Otherwise return { ok: true, doc } with the new document. Never modify the input doc.
Next: Mini Schema Validator