Apply set, remove, and push edits immutably, sharing refs
A collaborative editor receives changes from the server as small batches of edit operations, such as “set this field”, “remove that item”, “append a comment”. The client keeps its state immutable so React can skip re-rendering anything whose reference did not change. Implement applyEdits(state, edits), which applies a batch of edits and returns the next state without touching the current one.
applyEdits(state, edits) // => next state (or state itself if nothing changed)
state is a plain object or an array. edits is an array of operations, applied in order: each edit sees the result of the ones before it. Every path is a non-empty array of keys: strings for object keys, numbers for array indexes.
{ op: 'set', path, value } stores value at path.{ op: 'remove', path } removes the last key of path. On an array with a number key, the element is spliced out (later elements shift down). On an object, the key is deleted.{ op: 'push', path, value } appends value to the array at path. If nothing (or null) is there, it creates [value].state, anything inside it, or any edit value. The state can be deeply frozen.set and push, a container that is missing, undefined, or null on the path is created: an array if the key used on it is a number, otherwise an object. For remove, a missing path means there is nothing to remove.set whose value is already there (by Object.is; a missing value counts as undefined) and a remove of a key that does not exist change nothing and copy nothing. If the whole batch changes nothing (including an empty batch), return state itself.TypeError if a path has to go inside a primitive (string, number, boolean), or if push targets a value that is not an array.const state = {
doc: { title: 'Roadmap', tags: ['q3'] },
comments: [{ id: 'c1', text: 'Looks good' }, { id: 'c2', text: 'Typo in H2' }],
cursor: { line: 4 },
};
const next = applyEdits(state, [
{ op: 'set', path: ['doc', 'title'], value: 'Roadmap 2027' },
{ op: 'push', path: ['doc', 'tags'], value: 'planning' },
{ op: 'remove', path: ['comments', 0] },
]);
next.doc; // => { title: 'Roadmap 2027', tags: ['q3', 'planning'] }
next.comments; // => [{ id: 'c2', text: 'Typo in H2' }]
next.comments[0] === state.comments[1]; // => true (shared)
next.cursor === state.cursor; // => true (not edited)
state.doc.tags; // => ['q3'] (unchanged)
applyEdits({}, [{ op: 'set', path: ['blocks', 0, 'type'], value: 'heading' }]);
// => { blocks: [{ type: 'heading' }] }
applyEdits(state, [{ op: 'set', path: ['cursor', 'line'], value: 4 }]) === state; // => true
applyEdits(state, [{ op: 'remove', path: ['doc', 'author'] }]) === state; // => true
applyEdits(state, [{ op: 'push', path: ['doc', 'title'], value: 'x' }]);
// throws TypeError (title is not an array)