Event Emitter with Once
Problem statement
Implement an EventEmitter class with on, once, off, and emit.
Requirements
on(event, callback)subscribes and returns an unsubscribe function.once(event, callback)subscribes for only the next emit.off(event, callback)removes a callback.emit(event, ...args)calls listeners in subscription order.- Removing a listener during emit should not skip later listeners from the same emit cycle.
Requirements & constraints
- Listeners should run in subscription order.
- `off` should work for both `on` and `once` callbacks.
- Return an unsubscribe function from `on` and `once`.
How to approach Event Emitter with Once
The strategy an interviewer expects you to reach for.
Event emitters with once are pub/sub plus self-removing listeners — analytics “fire exactly one time” hooks. Naive move Register with on and remove after emit inside the callback. If emit is re-entrant or the callback throws, removal can be skipped or order gets weird. Where it breaks once must unsubscribe before invoking so recursive emits do not re-enter. Duplicate function references should not double-register if you use a Set. The fix Map event → Set of listeners. once wraps the callback, removes the wrapper first, then calls through. Snapshot listeners when emitting so mutations mid-emit are safe. Remember: once removes itself before calling; emit from a snapshot. Say this in the interview: I'd store listeners in a Set per event, wrap once-handlers so they unsubscribe before running, and emit over a copied list.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.