Implement an EventEmitter class. Code registers listeners (callback functions) for named events, and emit calls them.
on(event, listener)registerslistenerforevent. Registering the same function twice means it runs twice.once(event, listener)registers a listener that is removed just before its first call.off(event, listener)removes one registration oflistenerforevent: the earliest one, whether it came fromonoronce. Removing something that isn't registered does nothing.emit(event, ...args)calls every listener foreventwithargs, in the order they were registered. It returnstrueif the event had at least one listener andfalseotherwise.listenerCount(event)returns how many registrationseventhas.on,onceandoffreturn the emitter, so calls can be chained.
Changes during an emit: an emit calls exactly the listeners registered when it started. A listener removed by an earlier listener in the same emit still runs this time. A listener added during the emit first runs on the next emit. A once listener is removed before it runs, so if it emits the same event again, it doesn't run a second time.
Input: const e = new EventEmitter();
e.on('save', log);
e.emit('save', 'doc-1')
Output: true; log was called with 'doc-1'
Input: e.once('ready', fn); e.emit('ready'); e.emit('ready');
Output: fn is called once
Input: e.emit('nobody-listens')
Output: false