Performancemedium

Implement a reactive StoreData class

Implement a `StoreData` class with `addData(key, value)` and `listenToKey(key, callback)` methods. The callback fires whenever a specific key's value changes. This mirrors a simplified reactive store like Zustand or Redux.

Asked at Airbnb

#observer pattern#classes#reactivity

Answer

class StoreData {
  constructor() {
    this._data = {}
    this._listeners = {}  // key → Set of callbacks
  }

  addData(key, value) {
    const oldValue = this._data[key]
    this._data[key] = value

    // Notify listeners only if value changed
    if (oldValue !== value && this._listeners[key]) {
      this._listeners[key].forEach(cb => cb(value, oldValue))
    }
  }

  listenToKey(key, callback) {
    if (!this._listeners[key]) this._listeners[key] = new Set()
    this._listeners[key].add(callback)

    // Return unsubscribe function
    return () => this._listeners[key].delete(callback)
  }

  getData(key) {
    return this._data[key]
  }
}

// Usage
const store = new StoreData()

const unsub = store.listenToKey('count', (newVal, oldVal) => {
  console.log(`count changed: ${oldVal}${newVal}`)
})

store.addData('count', 1)   // "count changed: undefined → 1"
store.addData('count', 2)   // "count changed: 1 → 2"
store.addData('count', 2)   // (no event — same value)
unsub()
store.addData('count', 3)   // (no event — unsubscribed)

Source: frontendinterviewhandbook.com — Airbnb

Practise more Performance questions →