Build an Event Emitter
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write a class EventEmitter. on(name, listener) adds a listener for the event called name. once(name, listener) does the same, but the listener is removed just before its first call. off(name, listener) removes that listener, including one added with once; removing one that isn't there does nothing. All three return the emitter, so calls chain. emit(name, ...args) calls the event's listeners in the order they were added, passing args, and returns true if it had any listeners, false if not. The listeners an emit calls are fixed when it starts: one added or removed during the emit only counts from the next emit. Emitting "error" with no error listeners throws the first argument (or a new Error if there is none); with a listener, it's called like any other. The checks never add the same listener twice to one event.
Your code must pass
- Calls listeners in order with the emitted arguments
- on, once and off return the emitter, so calls chain
- emit returns whether any listener ran
- off removes a listener, including a once listener
- once listeners run only on the first emit
- Listeners added or removed during an emit wait for the next one
- Throws an unhandled error event