Apply JSON Patch add, remove, and replace operations
A notes app syncs user settings between devices. Instead of uploading the whole settings document after every change, each device sends a short list of edits such as “set /theme/accent to teal” or “remove the second pinned folder”. The other devices replay those edits on their own copy.
Implement applyPatch(document, operations). It applies the operations in order and returns the resulting document.
applyPatch(document, operations) // => new document
Each operation is an object with an op, a path, and (for add and replace) a value:
{ op: 'add', path, value }: on an object, sets the key (overwriting it if it exists). On an array, inserts value at the index and shifts later items right. The index can be equal to the array length, and the special token - means “append to the end”.{ op: 'remove', path }: deletes the key from an object, or removes the item from an array and shifts later items left. The target must exist.{ op: 'replace', path, value }: replaces an existing key or array item. The target must exist."" points at the whole document, and every other path is a list of tokens each starting with /, such as /folders/1/name.~1 stands for / and ~0 stands for ~. So /a~1b is the key "a/b", and /m~0n is the key "m~n".0 or a number without leading zeros (01 is invalid). - is only valid for add.add and replace on "" return value as the new document. remove on "" is an error.Error (any message) for an unknown op, a path that does not start with / (other than ""), a missing parent container, a missing target for remove/replace, or an invalid or out-of-range array index.document, the operations, or any value inside them. The result must not share objects with them either, so editing the result later cannot change the inputs.const settings = {
theme: { mode: 'dark', accent: 'blue' },
folders: ['Inbox', 'Work', 'Recipes'],
};
applyPatch(settings, [
{ op: 'replace', path: '/theme/accent', value: 'teal' },
{ op: 'remove', path: '/folders/1' },
{ op: 'add', path: '/folders/-', value: 'Travel' },
{ op: 'add', path: '/fontSize', value: 14 },
]);
// => {
// theme: { mode: 'dark', accent: 'teal' },
// folders: ['Inbox', 'Recipes', 'Travel'],
// fontSize: 14,
// }
// settings is unchanged.
applyPatch({ 'a/b': 1 }, [{ op: 'replace', path: '/a~1b', value: 2 }]); // => { 'a/b': 2 }
applyPatch(settings, [{ op: 'remove', path: '/folders/7' }]); // throws
null.