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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- Implement an Event Manager with on, off, once and emit. (Flipkart 2025, Livspace 2025)
- Make on return an unsubscribe function.
- What if a listener removes itself during emit?
- Add wildcard events or async listeners with error isolation. (Robinhood's three-stage version)
- Build a Redux-like store with subscribe and middleware. (Flipkart 2025)
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.