Keep two separate maps: one for the data and one for the listeners, keyed by event name (change:name for one key, change for all). set(key, value) compares the new value with the old one, stores it, and calls the listeners only if it really changed, passing the new value, the old value and the key. Keeping the maps apart is what makes the variation easy: unset(key) deletes from the data map and fires the change events, the listeners map is untouched, and a later set notifies the same listeners. Details interviewers check: don't fire when the value is unchanged, use has to tell a missing key from one set to undefined, return an unsubscribe function from on, and loop over a copy of the listeners so one that unsubscribes during the event doesn't disturb the rest.
Implement a Backbone-style StoreData class with key/value pairs and change listeners. One variation included a global change listener and required unset to remove data while retaining subscriptions. Setting the attribute again should notify those listeners. Source
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
data holds the values and listeners holds arrays of callbacks under names like change:name. set reads the old value, writes the new one, and emits only on a real change: a key that didn't exist, or a value that differs by Object.is (so NaN set twice is not a change). existed comes from has, not from comparing with undefined, so the first set('k', undefined) still counts.
// Key/value data plus listeners per key. A listener runs when its key's value really changes.class StoreData {constructor() {this.data = new Map();this.listeners = new Map(); // event name -> listeners}has(key) {return this.data.has(key);}get(key) {return this.data.get(key);}set(key, value) {const existed = this.data.has(key);const old = this.data.get(key);this.data.set(key, value);if (!existed || !Object.is(old, value)) this.emit(`change:${key}`, value, old, key);}on(event, listener) {if (!this.listeners.has(event)) this.listeners.set(event, []);this.listeners.get(event).push(listener);}emit(event, ...args) {for (const listener of this.listeners.get(event) ?? []) listener(...args);}}
passes 5 checks run on every build, against the native method where there is one
- set, get and has
- a key's listeners get the new value, the old value and the key
- setting the same value again doesn't notify
- listeners of other keys stay quiet; several listeners run in order
- the first set of a key to undefined still counts as a change
Every change now emits twice: change:<key> for that key's listeners, then change for listeners of the whole store. unset removes the value and reports the change with undefined as the new value; it never touches the listeners map, so subscriptions outlive the data. on returns a function that removes the listener, and emit loops over a copy so a listener can unsubscribe itself mid-event.
// The variation: a global `change` event, and unset() that removes the value but keeps the// subscriptions, so setting the key again notifies the same listeners. Plus unsubscribing.class StoreData {constructor() {this.data = new Map();this.listeners = new Map();}has(key) {return this.data.has(key);}get(key) {return this.data.get(key);}set(key, value) {const existed = this.data.has(key);const old = this.data.get(key);this.data.set(key, value);if (!existed || !Object.is(old, value)) this.changed(key, value, old);}// Data and listeners live in separate maps, so deleting the value leaves subscriptions alone.unset(key) {if (!this.data.has(key)) return;const old = this.data.get(key);this.data.delete(key);this.changed(key, undefined, old);}changed(key, value, old) {this.emit(`change:${key}`, value, old, key);this.emit('change', value, old, key);}// Returns a function that removes this listener.on(event, listener) {if (!this.listeners.has(event)) this.listeners.set(event, []);this.listeners.get(event).push(listener);return () => this.off(event, listener);}off(event, listener) {const list = this.listeners.get(event);const at = list ? list.indexOf(listener) : -1;if (at !== -1) list.splice(at, 1);}emit(event, ...args) {// A copy: a listener that unsubscribes while we loop must not make the next one get skipped.for (const listener of [...(this.listeners.get(event) ?? [])]) listener(...args);}}
passes 12 checks run on every build, against the native method where there is one
- set, get and has
- a key's listeners get the new value, the old value and the key
- setting the same value again doesn't notify
- listeners of other keys stay quiet; several listeners run in order
- the first set of a key to undefined still counts as a change
- the global change listener hears every key, after the key's own listeners
- unset removes the value and notifies
- subscriptions survive unset: setting the key again notifies them
- unset of a key that isn't there does nothing
- on returns an unsubscribe function; off removes one listener
- a listener that unsubscribes itself doesn't make the next one get skipped
- the global listener hears unset too
set({ a: 1, b: 2 }) follows Backbone's order: write every key, then emit change:key for each key that changed, then emit one change for the whole call, here with an object describing every change. Because all the writes land first, a listener reading other keys sees the final state, never a half-updated one. { silent: true } writes without events (for loading initial data), and once unsubscribes itself before calling its listener.
// Setting several keys at once, the way Backbone's set(attributes) works: write everything// first, then fire `change:key` for each key that changed, then one `change` for the call.class StoreData {constructor(initial = {}) {this.data = new Map(Object.entries(initial));this.listeners = new Map();}has(key) {return this.data.has(key);}get(key) {return this.data.get(key);}// set('name', 'Ana') or set({ name: 'Ana', age: 30 }); { silent: true } skips the events.set(key, value, options) {const entries = typeof key === 'object' && key !== null ? Object.entries(key) : [[key, value]];if (typeof key === 'object' && key !== null) options = value;this.apply(entries.map(([k, v]) => ({ key: k, value: v, remove: false })), options);}unset(key, options) {this.apply([{ key, remove: true }], options);}apply(writes, { silent = false } = {}) {const changes = {};for (const { key, value, remove } of writes) {const existed = this.data.has(key);const old = this.data.get(key);if (remove ? !existed : existed && Object.is(old, value)) continue; // nothing changesif (remove) this.data.delete(key);else this.data.set(key, value);changes[key] = { value, old };}// Every write has landed before the first listener runs, so listeners see the final state.if (silent || Object.keys(changes).length === 0) return;for (const [key, { value, old }] of Object.entries(changes)) this.emit(`change:${key}`, value, old, key);this.emit('change', changes);}on(event, listener) {if (!this.listeners.has(event)) this.listeners.set(event, []);this.listeners.get(event).push(listener);return () => this.off(event, listener);}once(event, listener) {const off = this.on(event, (...args) => {off();listener(...args);});return off;}off(event, listener) {const list = this.listeners.get(event);const at = list ? list.indexOf(listener) : -1;if (at !== -1) list.splice(at, 1);}emit(event, ...args) {for (const listener of [...(this.listeners.get(event) ?? [])]) listener(...args);}}
passes 16 checks run on every build, against the native method where there is one
- set, get and has
- a key's listeners get the new value, the old value and the key
- setting the same value again doesn't notify
- listeners of other keys stay quiet; several listeners run in order
- the first set of a key to undefined still counts as a change
- unset removes the value and notifies
- subscriptions survive unset: setting the key again notifies them
- unset of a key that isn't there does nothing
- on returns an unsubscribe function; off removes one listener
- a listener that unsubscribes itself doesn't make the next one get skipped
- set(object): each changed key's event, then one change with every change
- all writes land before the first listener runs
- nothing changed, nothing fired
- silent writes change the data without events
- the global change after unset reports the removed value
- once listens for a single change
Backbone.Model
The class this question is modelled on: set fires change:[attribute] for each changed attribute and then one change, unset removes an attribute and fires change, and { silent: true } suppresses the events.
State stores
Redux, Zustand and similar stores are the same pattern at a larger scale: state in one place, subscribe(listener) returning an unsubscribe function, and listeners called after a change.
EventTarget
The platform's own listener registry: addEventListener, removeEventListener and a once option, the same contract as on, off and once here.
Storing listeners next to the value, so removing the value also removes its subscriptions.
Notifying on every
set, even when the value didn't change.Comparing with
undefinedto decide whether a key exists, which breaks for a key set toundefined.Looping over the live listener array while a listener removes itself: the next listener is skipped.
No way to unsubscribe, which leaks listeners from components that have gone away.
Firing events for the first key of a multi-key update before the other keys are written.
How do you decide a value changed?
Object.is (or ===) compares identity, which is right for primitives. Two different objects with the same content count as a change; Backbone uses a deep comparison instead. Deep equality costs more and hides mutations of the same object, so say which you chose.
What if a listener calls set?
The nested set runs and emits its own events in the middle of the outer loop. That's usually accepted, but it can loop forever if two listeners keep changing each other's key, so some stores queue changes made during a notification.
What if a listener throws?
As written, the listeners after it don't run. A store can catch each listener's error and report it so one bad subscriber doesn't block the rest.
How would you support wildcard or nested keys?
For change:user.*, split the key into parts and notify listeners registered on each prefix, the way a DOM event bubbles from a node to its ancestors.