Skip to the page

Utility functions · core

EventEmitter, pub/sub and a mini Redux store

An EventEmitter keeps a Map from event name to a list of listeners, with on (returning an unsubscribe function), once, off and emit; the same subscribe-and-notify core is what a Redux-like store uses to tell the UI that state changed.

The notes

What you must know

  • Data: Map<string, Array<fn>> (allows duplicates) or Map<string, Set<fn>> (no duplicates).
  • emit: copy the listener list before looping, because a listener may remove itself or others; pass the arguments; optionally isolate errors with try/catch per listener; return whether any listener ran.
  • once: a wrapper that removes itself before calling fn. Store the original on the wrapper so off(name, original) can remove it.
  • on returns an unsubscribe closure. This is the shape React's useEffect cleanup and useSyncExternalStore expect.
  • Forgetting to unsubscribe leaks memory; Node warns when a name has too many listeners.
  • Typed events in TypeScript: on<K extends keyof Events>(name: K, fn: (payload: Events[K]) => void).
  • Mini store: getState, dispatch (reducer -> new state -> notify), subscribe. Don't allow dispatch inside the reducer. Add middleware by composition.

The red pen

Common traps: mistake → fix

  • Mistake: Changing the listener array while emit loops over it

    Fix: listeners are skipped.

  • Mistake: A once wrapper that off(name, original) can't remove.

  • Mistake: Notifying listeners before the state is updated.

Easy to hard

Questions interviewers ask, easy to hard

  1. Implement an Event Manager with on, off, once and emit. (Flipkart 2025, Livspace 2025)
  2. Make on return an unsubscribe function.
  3. What if a listener removes itself during emit?
  4. Add wildcard events or async listeners with error isolation. (Robinhood's three-stage version)
  5. Build a Redux-like store with subscribe and middleware. (Flipkart 2025)

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview