Event Emitter
MediumP1Coding
Implement a class EventEmitter with four methods:
on(event, listener): register a listener forevent. Returns the emitter so calls can be chained.off(event, listener): remove one registration of that listener. Removing a listener that is not registered does nothing. Returns the emitter.once(event, listener): likeon, but the listener runs at most once.off(event, listener)with the original function must also cancel aonceregistration that has not fired. Returns the emitter.emit(event, ...args): call every listener ofeventin registration order, passingargs. Returnstrueif there was at least one listener, otherwisefalse.
Edge rules: a listener that removes itself (or others) while emit is running must not cause listeners to be skipped in that same emit. The same function registered twice runs twice.
Example 1
- Input
- const e = new EventEmitter(); e.on('hi', n => log(n)); e.emit('hi', 1);
- Output
- log(1) runs; emit returns true
Constraints
- Event names are strings
- Listeners are functions
- At most 10^4 listeners per event
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 11. ⌘Enter runs, ⌘⇧Enter submits.