Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Build an EventEmitter

Object-Oriented Programminghard

Implement an `EventEmitter` class with `on(event, callback)` to subscribe, `off(event, callback)` to unsubscribe a specific callback, and `emit(event, ...args)` to call every subscriber of that event in registration order, forwarding the arguments. Multiple callbacks may listen to the same event.

Examples

Input: const e = new EventEmitter(); const out = []; e.on("msg", (x) => out.push(x)); e.emit("msg", 1); e.emit("msg", 2); out
Output: [1, 2]

Sample tests

Input: subscribers receive emitted values
Output: [1,2]
Input: off() removes the listener
Output: []

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Emitting an event that has no listeners should be a no-op, not a crash — default to an empty array.
  • Storing a single callback per event instead of an array drops additional subscribers.

Learning resources

  • MDN: Classes
Approach & explanation (try first)

The emitter keeps a map from event name to an ordered list of callbacks. `on` appends, `off` filters by reference, and `emit` iterates the list forwarding the arguments. This is the core publish/subscribe pattern behind Node's EventEmitter and browser event targets.

Loading...
⌘/Ctrl + Enter

Run your code to see results.