coding round · ~20 min
JavaScriptintermediate

Build an event emitter

Implement a class EventEmitter with these methods:

  • on(event, listener) registers a listener and returns this
  • off(event, listener) removes that listener (also when it was added with once) and returns this
  • once(event, listener) registers a listener that is removed just before its first run, and returns this
  • emit(event, ...args) calls the listeners for event in the order they were added, passing args, and returns true if the event had listeners and false otherwise (like Node)

Removing listeners while an event is being emitted (for example, a once listener removing itself) must not cause other listeners of that same emit to be skipped. Removing an unknown listener or event does nothing.

  • emitter.on('greet', (name) => console.log('hi ' + name)), then emitter.emit('greet', 'Ada') → logs hi Ada and returns true
  • emitter.emit('nothing') → false
  • after emitter.once('ready', fn), the first emit('ready') calls fn and the second returns false

Define EventEmitter in the editor. 7 tests will call it.

solution.js
class EventEmitter {
  constructor() {
    // Store the listeners for each event name.
  }

  on(event, listener) {}

  off(event, listener) {}

  once(event, listener) {}

  emit(event, ...args) {
    // Return true if the event had listeners, false otherwise.
  }
}

Tests⌘/Ctrl + Enter to run

calls listeners in order with the emitted arguments
emit returns true if the event had listeners, false otherwise
off removes only the given listener
once listeners run a single time
off can remove a once listener before it fires
removing listeners during emit does not skip the others
methods are chainable and events are independent
esc