32Implement an EventEmitter with on, off, emit, and once
mediumAbout 35 minutesCodingeventsclassespub-sub
Problem
Implement an EventEmitter class, similar to Node's:
on(event, listener): add a listener. Returns the emitter, so calls can be chained.once(event, listener): add a listener that removes itself after its first call.off(event, listener): remove a listener. Works for listeners added withoncetoo.emit(event, ...args): call every listener foreventin the order they were added, withthisset to the emitter. Returntrueif there were listeners, otherwisefalse.listenerCount(event): the number of listeners forevent.
const chat = new EventEmitter();
const onMessage = (from, text) => console.log(`${from}: ${text}`);
chat.on("message", onMessage);
chat.once("message", () => console.log("first message!"));
chat.emit("message", "Asha", "Hi"); // both listeners run
chat.emit("message", "Ravi", "Hello"); // only onMessage runs
chat.off("message", onMessage);Requirements
- The same listener added twice is called twice, and
offremoves one of them (the most recently added). - A listener that removes itself, or another listener, during
emitmust not cause others to be skipped. - A listener added during
emitis not called in that sameemit. onthrows aTypeErrorwhen the listener is not a function.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Video walkthroughs
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
Use a Map from event name to an array of listeners. A Map accepts any event name, including "constructor" or a Symbol, without clashing with object properties.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.