Implement an Immer-style producer with copy-on-write drafts
State libraries such as Redux want every update to return a new state object and leave the old one untouched, so a change can be detected with ===. Writing those updates by hand with nested spreads is tedious and easy to get wrong. A copy-on-write producer lets you write plain mutations against a draft, and turns them into a new immutable state behind the scenes.
Implement produceState(base, recipe).
produceState(base, recipe) // => nextState
base: the current state, a plain object or an array. It can be deeply frozen.recipe(draft): a function you call once with a draft of base. The recipe reads and mutates the draft as if it were a normal object.draft.board.columns[1].title = 'Doing' works.delete-ing properties.push, pop, shift, unshift, splice, sort, reverse, index assignment, and assigning length.Array.isArray(draft), Object.keys(draft), key in draft, spread, and JSON.stringify(draft) behave as they would on the current value.draft.featured = draft.items[0].base, at any depth.base. Every object or array that changed, and all of its ancestors, is a new object.base itself.Object.is) is not a change. Deleting a key that does not exist is not a change. Tests do not check writes that are undone later in the same recipe.undefined (or the root draft), the result is built from the draft. If it returns any other value, that value is the result and the draft’s changes are discarded.Object.prototype or null) and arrays are drafted. Other values, such as a Date or a Map, are kept by reference. Recipes never mutate them.produceState returns or throws, every draft it created is unusable: reading or writing one throws a TypeError.base is unchanged.const board = {
name: 'Sprint 14',
columns: [
{ title: 'Todo', cards: [{ id: 'c1', text: 'Write spec' }] },
{ title: 'Done', cards: [] },
],
owner: { name: 'Lena' },
};
const next = produceState(board, (draft) => {
const [todo, done] = draft.columns;
done.cards.push(todo.cards.shift());
draft.name = 'Sprint 14 (closed)';
});
next.columns[1].cards; // => [{ id: 'c1', text: 'Write spec' }]
next.columns[0].cards; // => []
board.columns[0].cards.length; // => 1 (base is untouched)
next.owner === board.owner; // => true (unchanged branch is shared)
next.columns[1].cards[0] === board.columns[0].cards[0]; // => true (the card itself did not change)
produceState(board, (draft) => {
draft.owner.name = 'Lena'; // same value
}) === board; // => true
produceState(board, () => ({ name: 'Fresh', columns: [], owner: null }));
// => { name: 'Fresh', columns: [], owner: null }
let leaked;
produceState(board, (draft) => { leaked = draft; });
leaked.name; // throws TypeError
Proxy (in particular Proxy.revocable) is the natural tool here.