Build a persistent map like Immutable.js: a hash array mapped trie, structural sharing, collisions and deletes

hardAbout 65 minutesUpdated CodingProjavascriptdata-structuresimmutabilityhamthashingtrie
Not solved

Share this question

Problem

Immutable.js, Clojure and Scala keep old versions of a map around for undo, time travel debugging and cheap === change checks, without copying the whole map on every update. Their maps are hash array mapped tries (HAMT): a wide tree indexed by the bits of each key's hash, where an update copies only the nodes on one root-to-leaf path and shares everything else with the old version.

const v1 = PersistentMap.empty().set("theme", "dark").set("lang", "en");
const v2 = v1.set("lang", "hi");
v1.get("lang"); // "en"
v2.get("lang"); // "hi"
v2.set("lang", "hi") === v2; // true

Ref. UR-1445 · © UIRound · uiround.com/questions/build-a-persistent-map-like-immutable-js-a-hash-array-mapped-trie-structural-sharing-collisions-and-deletes

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment