Implement an EventEmitter (pub/sub) with on, off, once and emit.
Requirements
on(event, listener)registers a listener and returns an unsubscribe function (a handy API for React/Vue cleanups).off(event, listener)removes it.once(event, listener)runs the listener at most once.emit(event, ...args)calls listeners in registration order and returns whether there were any.
Pitfalls
- Removing a listener while emitting (for example a
oncelistener) must not skip the next one: iterate over a copy of the list. offwith aoncelistener: keep a link from the wrapper to the original so it can be removed by the original reference.- One failing listener should not stop the others in some designs (report the error and continue), but Node's EventEmitter lets it throw; state your choice.
The same pattern powers DOM events, Node's EventEmitter, mitt, and the message bus between micro-frontends.
js
class EventEmitter {
#listeners = new Map(); // event -> array of listeners
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);
if (!list) return;
const i = list.findIndex(l => l === listener || l.original === listener);
if (i !== -1) list.splice(i, 1);
if (list.length === 0) this.#listeners.delete(event);
}
once(event, listener) {
const wrapper = (...args) => {
this.off(event, wrapper);
listener.apply(this, args);
};
wrapper.original = listener;
return this.on(event, wrapper);
}
emit(event, ...args) {
const list = this.#listeners.get(event);
if (!list) return false;
for (const listener of [...list]) listener.apply(this, args); // copy: safe if listeners unsubscribe
return true;
}
listenerCount(event) {
return this.#listeners.get(event)?.length ?? 0;
}
}
// Demo
const bus = new EventEmitter();
const log = [];
const unsubscribe = bus.on('login', user => log.push(`welcome ${user}`));
bus.once('login', user => log.push(`first login ${user}`));
bus.on('login', user => log.push(`audit ${user}`));
assert.equal(bus.emit('login', 'asha'), true);
assert.deepEqual(log, ['welcome asha', 'first login asha', 'audit asha']);
unsubscribe();
bus.emit('login', 'ravi');
assert.deepEqual(log.slice(3), ['audit ravi']); // once ran only once, welcome was removed
assert.equal(bus.listenerCount('login'), 1);
assert.equal(bus.emit('logout'), false);
console.log(log);Example
Subscribing from a React component and cleaning up with the returned function:
jsx
function Notifications({ bus }) {
const [items, setItems] = useState([]);
useEffect(() => bus.on('notify', msg => setItems(prev => [...prev, msg])), [bus]); // returns unsubscribe
return <ul>{items.map((m, i) => <li key={i}>{m}</li>)}</ul>;
}Because on returns the unsubscribe function, it can be returned straight from useEffect as the cleanup.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you add wildcard listeners such as 'user.*'?
Store wildcard patterns separately, and in emit also call listeners whose pattern matches the event (convert user.* to a regular expression once at registration). Keep exact-match lookups in the Map so the common path stays O(1).