Skip to curriculum
Jump to the editor

19.11. Update an object immutably with commands

Medium
Topics
20–35 min

State in a reducer or a component must not be changed in place: code that compares old and new state with === (a memoized selector, a list row that skips re-rendering) only sees a change when the changed object, and every object above it, is new. Writing those copies by hand for a deep path is long and easy to get wrong. A small command language makes it one call: describe the change, get a new value back, and keep sharing everything the change did not touch.

Write update(target, spec) in update.js. It returns an updated copy of target and never changes target.

Signature

JAVASCRIPT
function update(target, spec) // returns the updated value
  • target: the value to update. Objects in it are plain objects and arrays.
  • spec: an object. A key that starts with $ is a command applied to the value at that point. Any other key walks into that property (or array index) of the value, with its own spec.

The commands:

CommandArgumentResult
$setany valuethat value
$unsetan array of keysthe object without those keys
$mergean objectthe object with those keys copied over it (shallow)
$pushan array of itemsthe array with the items added at the end
$unshiftan array of itemsthe array with the items added at the front
$splicean array of argument arraysthe array after each splice(...arguments), in order
$applya functionwhat the function returns when called with the old value

Requirements

  1. A command at the top of spec applies to target itself.
  2. Walking into a key copies only the objects and arrays on the path to the change. Every other branch is the same object as in target (===). Arrays stay arrays.
  3. target is never changed: the tests freeze it deeply.
  4. When nothing changes, the result is target itself, at every level. Values are compared with Object.is. Nothing changes for a $set or $apply that gives the same value, a $merge whose values are already there, an $unset of missing keys, a $push or $unshift of no items, an empty $splice list and an empty spec. A $set that adds a missing key is a change, even with undefined.
  5. Several keys in one spec all apply. $push adds an array item as one item (it does not flatten it). $splice runs its calls in order on one copy.
  6. $push, $unshift and $splice throw a TypeError when the value is not an array, or when their argument (or a $splice call) is not an array. $merge and $unset throw a TypeError when the value is not an object, and $apply when its argument is not a function.
  7. An unknown command (any $ key not in the table, including names like $toString) throws an Error. A spec with a command and other keys next to it throws an Error.
  8. A spec value that is not an object, and walking into a value that is not an object, throw a TypeError.
  9. spec is not changed.
  10. Keys are own data: a key the target does not own counts as missing (its current value is undefined), and every key that is written, "__proto__" included (as JSON.parse makes it), becomes an own field of the copy without changing its prototype.

Examples

JAVASCRIPT
const state = {
  user: { name: "Ada", tags: ["admin"] },
  settings: { theme: "dark" },
};

const next = update(state, { user: { name: { $set: "Grace" } } });
next.user.name;                         // "Grace"
next.settings === state.settings;       // true: not touched, so shared
next.user.tags === state.user.tags;     // true
state.user.name;                        // "Ada": the input is unchanged
JAVASCRIPT
update({ list: [1, 2, 3, 4] }, { list: { $splice: [[1, 2], [0, 0, "a"]] } });
// { list: ["a", 1, 4] }

update({ count: 1 }, { count: { $apply: (n) => n + 1 } });
// { count: 2 }

update({ a: 1, b: 2 }, { $unset: ["a"] });
// { b: 2 }
JAVASCRIPT
const same = { a: { b: 1 } };
update(same, { a: { b: { $set: 1 } } }) === same;   // true: nothing changed

update({ text: "hi" }, { text: { $push: ["!"] } });  // throws TypeError
update({ a: 1 }, { a: { $add: 1 } });                // throws Error: unknown command

Environment

  • Plain JavaScript in a browser page; the tests call the global update from update.js.
  • Objects other than plain objects and arrays (Map, Date, class instances) are out of scope; copy objects with their own enumerable keys.
  • Paths written as strings ("user.name") are not part of this problem.

Hints

  1. Each nested spec is itself a call to update on one smaller value. When does the parent need a copy?
  2. How can you tell that a nested call changed nothing, without comparing whole objects?

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…