19.11. Update an object immutably with commands
Topics
This question is in
19. Events, state and historyState 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
function update(target, spec) // returns the updated valuetarget: 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:
| Command | Argument | Result |
|---|---|---|
$set | any value | that value |
$unset | an array of keys | the object without those keys |
$merge | an object | the object with those keys copied over it (shallow) |
$push | an array of items | the array with the items added at the end |
$unshift | an array of items | the array with the items added at the front |
$splice | an array of argument arrays | the array after each splice(...arguments), in order |
$apply | a function | what the function returns when called with the old value |
Requirements
- A command at the top of
specapplies totargetitself. - 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. targetis never changed: the tests freeze it deeply.- When nothing changes, the result is
targetitself, at every level. Values are compared withObject.is. Nothing changes for a$setor$applythat gives the same value, a$mergewhose values are already there, an$unsetof missing keys, a$pushor$unshiftof no items, an empty$splicelist and an empty spec. A$setthat adds a missing key is a change, even withundefined. - Several keys in one spec all apply.
$pushadds an array item as one item (it does not flatten it).$spliceruns its calls in order on one copy. $push,$unshiftand$splicethrow aTypeErrorwhen the value is not an array, or when their argument (or a$splicecall) is not an array.$mergeand$unsetthrow aTypeErrorwhen the value is not an object, and$applywhen its argument is not a function.- An unknown command (any
$key not in the table, including names like$toString) throws anError. A spec with a command and other keys next to it throws anError. - A spec value that is not an object, and walking into a value that is not an object, throw a
TypeError. specis not changed.- 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 (asJSON.parsemakes it), becomes an own field of the copy without changing its prototype.
Examples
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 unchangedupdate({ 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 }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 commandEnvironment
- Plain JavaScript in a browser page; the tests call the global
updatefromupdate.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
- Each nested spec is itself a call to
updateon one smaller value. When does the parent need a copy? - 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