Build an ObservableMap that emits set, delete and clear events to its listeners

mediumAbout 35 minutesUpdated CodingPromapseventsclassesobserver-patterndata-structures
Not solved

Share this question

Problem

State libraries, caches and devtools all need to know when a collection changes. Implement class ObservableMap extends Map: a normal Map (same constructor, get, has, size, iteration) that also tells listeners about every change.

const prices = new ObservableMap([["apple", 1]]);
const stop = prices.on("set", ({ key, value, previous, isNew }) => {
  console.log(key, previous, "→", value, isNew ? "(new)" : "");
});
prices.set("apple", 2).set("pear", 3); // apple 1 → 2   then   pear undefined → 3 (new)
prices.set("pear", 3);                 // nothing: the value did not change
stop();
prices.on("change", (e) => console.log(e.type));
prices.delete("apple");                // delete
prices.clear();                        // clear

Ref. UR-1467 · © UIRound · uiround.com/questions/build-an-observablemap-that-emits-set-delete-and-clear-events-to-its-listeners

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