Implement an EventEmitter
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement an EventEmitter class, the pattern behind Node's events module, DOM events and most pub/sub code. Listeners subscribe to an event by name, and emit calls all of them with the given arguments.
const emitter = new EventEmitter()
const greet = (name) => console.log(`Hello, ${name}`)
emitter.on('join', greet)
emitter.emit('join', 'Dana') // logs "Hello, Dana", returns true
emitter.off('join', greet)
emitter.emit('join', 'Noa') // logs nothing, returns false
emitter.once('ready', () => console.log('ready'))
emitter.emit('ready') // logs "ready"
emitter.emit('ready') // logs nothingRequirements
on(eventName, listener)registers a listener and returns the emitter, so calls can be chained.once(eventName, listener)registers a listener that is removed right before its first call. It also returns the emitter.off(eventName, listener)removes one registration of that listener and returns the emitter. Removing a listener that isn't registered does nothing. Aoncelistener can be removed withoffbefore it fires.emit(eventName, ...args)calls every listener of that event in the order they were added, withargs. It returnstrueif the event had listeners, andfalseotherwise.- The same listener can be added more than once, and is then called once per registration.
- Listeners added or removed while an
emitis running don't change which listeners thatemitcalls. - Each emitter has its own listeners.
Approach
Store a Map from event name to an array of entries, one entry per registration: { listener, once }.
on/once: push a new entry, creating the array on first use. Returnthis.off: find the first entry whoselistenermatches andspliceit out. Matching on the original listener (not a wrapper) is what letsoffremove aoncelistener. Returnthis.emit: if there are no entries, returnfalse. Otherwise loop over a copy of the array. For each entry, remove it first if it is aonceentry, then call the listener with the arguments. Returntrue.
Why emit loops over a copy
Listeners often change the list while it is being emitted: a once listener removes itself, or a listener calls off on another one. Removing an item from an array you are looping over by index shifts the remaining items left, so the next listener gets skipped. Looping over a snapshot ([...entries]) keeps that emit stable, and changes only affect the next one.
Why once removes before it calls
If the listener emits the same event again from inside itself, a once entry that is still registered would be called a second time. Removing it first guarantees "at most once" even with re-entrant emits.
Why entries instead of a Set
A Set can't hold the same listener twice, and the requirements allow duplicates. Storing entries also gives each registration its own once flag.
Complexity
on, once and the false case of emit are O(1). off is O(k) and emit is O(k) for k listeners of that event (plus O(k) for each once removal).
Follow-ups interviewers ask
- Return an unsubscribe function from
on, which many modern APIs (Reduxsubscribe,useSyncExternalStore) do instead ofoff. - Error handling: should one throwing listener stop the others? Node rethrows; a UI event bus might catch and report each error instead.
- Typed events in TypeScript: a generic
EventEmitter<Events>whereEventsmaps event names to argument tuples, soemit('join', 42)is a type error. - Memory leaks: listeners that are never removed keep their closures alive. Node warns once an event passes
maxListeners.
Reference solution
export default class EventEmitter {
#events = new Map()
/**
* @param {string} eventName
* @param {Function} listener
* @returns {EventEmitter}
*/
on(eventName, listener) {
return this.#add(eventName, listener, false)
}
/**
* @param {string} eventName
* @param {Function} listener
* @returns {EventEmitter}
*/
once(eventName, listener) {
return this.#add(eventName, listener, true)
}
/**
* @param {string} eventName
* @param {Function} listener
* @returns {EventEmitter}
*/
off(eventName, listener) {
const entries = this.#events.get(eventName)
const entry = entries?.find((candidate) => candidate.listener === listener)
if (entry) this.#remove(eventName, entry)
return this
}
/**
* @param {string} eventName
* @param {...*} args
* @returns {boolean}
*/
emit(eventName, ...args) {
const entries = this.#events.get(eventName)
if (!entries || entries.length === 0) return false
for (const entry of [...entries]) {
if (entry.once) this.#remove(eventName, entry)
entry.listener.apply(this, args)
}
return true
}
#add(eventName, listener, once) {
const entries = this.#events.get(eventName) ?? []
entries.push({ listener, once })
this.#events.set(eventName, entries)
return this
}
#remove(eventName, entry) {
const entries = this.#events.get(eventName)
if (!entries) return
const index = entries.indexOf(entry)
if (index !== -1) entries.splice(index, 1)
if (entries.length === 0) this.#events.delete(eventName)
}
}type Listener = (...args: any[]) => void
type Entry = { listener: Listener; once: boolean }
export default class EventEmitter {
#events = new Map<string, Entry[]>()
on(eventName: string, listener: Listener): this {
return this.#add(eventName, listener, false)
}
once(eventName: string, listener: Listener): this {
return this.#add(eventName, listener, true)
}
off(eventName: string, listener: Listener): this {
const entries = this.#events.get(eventName)
const entry = entries?.find((candidate) => candidate.listener === listener)
if (entry) this.#remove(eventName, entry)
return this
}
emit(eventName: string, ...args: unknown[]): boolean {
const entries = this.#events.get(eventName)
if (!entries || entries.length === 0) return false
for (const entry of [...entries]) {
if (entry.once) this.#remove(eventName, entry)
entry.listener.apply(this, args)
}
return true
}
#add(eventName: string, listener: Listener, once: boolean): this {
const entries = this.#events.get(eventName) ?? []
entries.push({ listener, once })
this.#events.set(eventName, entries)
return this
}
#remove(eventName: string, entry: Entry) {
const entries = this.#events.get(eventName)
if (!entries) return
const index = entries.indexOf(entry)
if (index !== -1) entries.splice(index, 1)
if (entries.length === 0) this.#events.delete(eventName)
}
}