Skip to curriculum
Jump to the editor

19.14. Produce immutable updates from a draft

Hard
Topics
45–60 min

State libraries compare old and new state by reference: if state.todos is the same object as before, nothing in the todo list re-renders. That needs immutable updates, a new object for everything on the path to a change and the old objects everywhere else. Written by hand, a change three levels deep is a pile of spreads. A draft fixes that: the code changes a stand-in for the state as if it were mutable, and the library builds the immutable result from the changes.

Write produce(base, recipe) in produce.js.

Signature

JAVASCRIPT
function produce(base, recipe) // returns the next version of base
  • base: a plain object (its prototype is Object.prototype or null) or an array. It is never changed.
  • recipe(draft): changes draft with ordinary JavaScript (assignment, delete, push, splice, sort...), or returns a new value.

Requirements

  1. base is never changed, at any depth (the tests freeze it).
  2. The result has every change the recipe made. Every object on the path to a change is a new object; every other object is the very same object as in base (===), including siblings of changed objects and unchanged objects inside changed ones.
  3. When nothing changed, the result is base itself. Reading is not a change, and assigning a value that is Object.is-equal to the current one is not a change.
  4. Inside the recipe, the draft behaves like the data: nested plain objects and arrays are drafts too, in, Object.keys and JSON.stringify see the changes made so far, Array.isArray is true for arrays, and the built-in array methods work.
  5. A draft placed somewhere else, directly (draft.backup = draft.meta) or inside a new object, ends up in the result as its final value. A draft met twice gives the same object twice. A new object that the recipe froze cannot hold a draft: produce throws a TypeError instead.
  6. New objects that the recipe assigns are kept as they are. Values that are not plain objects or arrays (Date, Map, class instances) are not drafted.
  7. Copies keep the prototype of the object they copy (a null-prototype object stays one) and all its own enumerable properties: symbol keys too, and an array's extra properties besides its items.
  8. A recipe that returns a value other than undefined makes that value the result (drafts inside it become their final values). Returning the draft itself is the same as returning nothing. Changing the draft and returning a different value throws an Error.
  9. After produce returns or throws, every draft stops working: any use of one throws a TypeError. An error thrown by the recipe comes out of produce unchanged.
  10. produce throws a TypeError when base is not a plain object or array, or recipe is not a function.

Examples

JAVASCRIPT
const state = {
  user: { name: "Asha", prefs: { theme: "dark" } },
  todos: [{ id: 1, done: false }, { id: 2, done: false }],
};

const next = produce(state, (draft) => {
  draft.todos[1].done = true;
  draft.todos.push({ id: 3, done: false });
});

next.todos[1].done;              // true
state.todos[1].done;             // false: state is unchanged
next.user === state.user;        // true: not touched
next.todos[0] === state.todos[0];// true: not touched
next.todos === state.todos;      // false: on the path to a change
JAVASCRIPT
produce(state, (draft) => { draft.user.name = "Asha"; }) === state;   // true: same value
produce(state, () => ({ reset: true }));                              // { reset: true }
JAVASCRIPT
let kept;
produce(state, (draft) => { kept = draft; });
kept.user;   // TypeError: the draft no longer works

Environment

  • Plain JavaScript in a browser page; the tests call the global produce from produce.js.
  • Proxy, Proxy.revocable, Reflect and WeakMap are allowed.
  • Drafting Map, Set and class instances, freezing the result, patches, and nested calls to produce are not part of this problem.

Hints

  1. A change deep inside means every ancestor needs a copy. When the deepest draft changes, how does it reach its ancestors?
  2. If a draft is created only when the recipe reads an object, and copied only when something changes, what does an object the recipe never touched cost?
  3. When the recipe ends, the copies may still hold drafts. What has to happen to them before the drafts are revoked?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…