JavaScriptFundamental (ES6), part 2
Persistent immutable map in JavaScript
113 A persistent map that shares almost all of itself
hardImmutable does not have to mean copied. Build a persistent sorted map as a binary search tree where insert returns a new root but rebuilds only the nodes along the path it changed, leaving every other subtree untouched and shared. Prove the sharing with === rather than by claim, count the nodes allocated per insert, and show the older version still reads exactly as it did. Add the identity short-circuit — inserting a value that is already there returns the very same tree — and do the same trick for a linked list whose tail is shared.
Stuck? Three hints, smallest first
- 1. A node is
{ key, value, left, right }and is never mutated. Insert returns a new node whose other child is the old child, passed straight through. - 2. Count allocations in the node factory. If the number is the depth of the path you walked rather than the size of the tree, you have structural sharing.
- 3. If the key is present and the value is identical, return the node you were given. That one line makes a no-op insert free, and it propagates all the way up.
let allocated = 0;
const node = (key, value, left, right) => {
allocated++;
return Object.freeze({ key, value, left, right });
};
const insert = (tree, key, value) => {
if (tree === null) return node(key, value, null, null);
if (key === tree.key) {
if (tree.value === value) return tree; // nothing to change
return node(key, value, tree.left, tree.right);
}
if (key < tree.key) {
const left = insert(tree.left, key, value);
return left === tree.left ? tree : node(tree.key, tree.value, left, tree.right);
}
const right = insert(tree.right, key, value);
return right === tree.right ? tree : node(tree.key, tree.value, tree.left, right);
};
const get = (tree, key) => {
let at = tree;
while (at !== null) {
if (key === at.key) return at.value;
at = key < at.key ? at.left : at.right;
}
return undefined;
};
const entries = (tree, out = []) => {
if (tree === null) return out;
entries(tree.left, out);
out.push([tree.key, tree.value]);
entries(tree.right, out);
return out;
};
const size = (tree) => (tree === null ? 0 : 1 + size(tree.left) + size(tree.right));
// Keys chosen so the tree is balanced: 'm' at the root, 'e' and 't' below it.
let version1 = null;
for (const [key, value] of [['m', 1], ['e', 2], ['t', 3], ['c', 4], ['g', 5], ['p', 6], ['w', 7]]) {
version1 = insert(version1, key, value);
}
const buildCost = allocated;
allocated = 0;
const version2 = insert(version1, 'f', 8);
const insertCost = allocated;
const bothReadable = [entries(version1).length, entries(version2).length, get(version1, 'f'), get(version2, 'f')];
const oldOneUnchanged = entries(version1).map(([k]) => k).join('');
// The right-hand subtree was not on the path, so it is the very same object.
const sharing = [
version2.right === version1.right,
version2.left === version1.left,
version2.left.left === version1.left.left,
version2 === version1,
];
const totalNodes = [size(version1), size(version2), insertCost];
allocated = 0;
const version3 = insert(version2, 'f', 8);
const noopInsert = [version3 === version2, allocated];
allocated = 0;
const version4 = insert(version2, 'f', 99);
const changedValue = [version4 === version2, allocated, get(version4, 'f'), get(version2, 'f')];
const frozenWrite = (() => {
try { version1.value = 'tampered'; return 'no error'; } catch (err) { return err.name; }
})();
// The same idea, one dimension down: a cons list sharing its tail.
let listAllocated = 0;
const cons = (head, tail) => { listAllocated++; return Object.freeze({ head, tail }); };
const toArray = (list) => { const out = []; for (let at = list; at !== null; at = at.tail) out.push(at.head); return out; };
listAllocated = 0;
let queue = null;
for (const till of ['Balogun 1', 'Balogun 2', 'Ikeja 1']) queue = cons(till, queue);
const threeCost = listAllocated;
const branchA = cons('Yaba', queue);
const branchB = cons('Ojota', queue);
const listSharing = [branchA.tail === queue, branchB.tail === queue, branchA.tail === branchB.tail];
const listCost = [listAllocated, toArray(branchA), toArray(branchB).length];
console.log('build cost :', buildCost, 'nodes; one insert cost', insertCost);
console.log('sharing :', sharing);
console.log('old version :', oldOneUnchanged);
console.log('list sharing :', listSharing, 'for', listCost[0], 'nodes total');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('building seven keys costs 17 nodes, because each insert copies its own path', [buildCost, bothReadable], [17, [7, 8, undefined, 8]]);
test('the older version is untouched: same keys, in order, without the new one', oldOneUnchanged, 'cegmptw');
test('yet one more insert rebuilt only that path: four nodes, for a tree of eight', totalNodes, [7, 8, 4]);
test('so the subtree off the path is literally the same object', sharing, [true, false, true, false]);
test('inserting a value that is already there returns the identical tree, free', noopInsert, [true, 0]);
test('changing that value does allocate, and each version keeps its own', changedValue, [false, 4, 99, 8]);
test('and the nodes are frozen, so a stray write throws under strict mode', frozenWrite, 'TypeError');
test('a cons list shares its whole tail with both branches built from it', listSharing, [true, true, true]);
test('so two five-element lists cost five nodes between them, not ten', listCost, [5, ['Yaba', 'Ikeja 1', 'Balogun 2', 'Balogun 1'], 4]);
Structural sharing is the idea that makes immutable data affordable, and the fourth assertion is the whole of it: version2.right === version1.right. Inserting 'f' allocated four nodes — the new leaf plus the three ancestors on the path to it — and handed every other subtree straight through by reference, so a tree of eight entries exists alongside the tree of seven for the price of four objects. Cost is the depth, O(log n), not the size. Copying the whole map on every write is what people assume immutability means, and it is why they conclude it is too slow.
The first assertion is the price you do pay, stated honestly: building those seven keys one insert at a time allocated 17 nodes, not 7, because every insert copies its own path and most of those copies are immediately superseded. Persistent structures are cheap to update and not free to build, which is why libraries offer a transient or mutable-batch mode for bulk loading and then seal it once.
The identity short-circuit is small and does a lot. insert returns the node it was given when nothing changed, and because each level checks whether its child came back unchanged, that answer propagates all the way to the root and the caller gets back the identical tree. Downstream, a prevProps === nextProps check then skips work correctly rather than by luck, which is exactly how a reference-equality render guard is supposed to earn its keep.
Two cautions. This tree has no balancing, so inserting sorted keys degenerates into a linked list and O(log n) becomes O(n) — real persistent maps use a red-black tree or a hash-array-mapped trie for that reason. And Object.freeze here is one level deep, which is enough because no node is ever mutated by this code; it is a guard against a caller, and under the strict mode these panels run in it throws rather than failing silently, which is the behaviour you want.