Build an ObservableMap that emits set, delete and clear events to its listeners
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(); // clearRef. UR-1467 · © UIRound · uiround.com/questions/build-an-observablemap-that-emits-set-delete-and-clear-events-to-its-listeners
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 6
- edge cases
- 4
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Extend
Mapso every existing method keeps working, and override only the three that change it. Each override does the real work withsuper, then tells the listeners. When should it stay silent?
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.