Event Emitter - Problem
Design an Event Emitter - Build a powerful event management system similar to Node.js EventEmitter or DOM Event Target!

Your task is to create an EventEmitter class that manages event subscriptions and emissions. This is a fundamental pattern used in many JavaScript frameworks and backend systems.

Key Requirements:

  • subscribe(eventName, callback) - Register listeners for events. Multiple callbacks can subscribe to the same event and will be called in subscription order. Returns an object with an unsubscribe() method.
  • emit(eventName, args) - Trigger all callbacks for an event with optional arguments. Returns an array of all callback results in subscription order, or empty array if no listeners.

Example: emitter.subscribe('click', () => 'Button clicked!') then emitter.emit('click') returns ['Button clicked!']

Input & Output

example_1.js โ€” Basic Subscribe and Emit
$ Input: const emitter = new EventEmitter(); const sub = emitter.subscribe('click', () => 'Button clicked!'); const result = emitter.emit('click');
โ€บ Output: ['Button clicked!']
๐Ÿ’ก Note: Single subscription returns array with one callback result
example_2.js โ€” Multiple Subscriptions
$ Input: const emitter = new EventEmitter(); emitter.subscribe('test', (x) => x * 2); emitter.subscribe('test', (x) => x + 1); const result = emitter.emit('test', [5]);
โ€บ Output: [10, 6]
๐Ÿ’ก Note: Multiple callbacks called in subscription order: 5*2=10, then 5+1=6
example_3.js โ€” Unsubscribe
$ Input: const emitter = new EventEmitter(); const sub = emitter.subscribe('data', () => 'received'); sub.unsubscribe(); const result = emitter.emit('data');
โ€บ Output: []
๐Ÿ’ก Note: After unsubscribing, no callbacks remain so emit returns empty array

Constraints

  • 1 โ‰ค number of operations โ‰ค 104
  • Event names are non-empty strings with length โ‰ค 100
  • Callback functions will not be referentially identical
  • Order matters: Callbacks must be called in subscription order

Visualization

Tap to expand
EventEmitter Hash Map ArchitectureHash Mapclickloaderror"click" Callbacks Arrayfn1fn2fn3O(1) Lookup!emit('click') directly finds callbacksExecutes: fn1() โ†’ fn2() โ†’ fn3()
Understanding the Visualization
1
Hash Map Structure
Events stored as key-value pairs: event name โ†’ callback array
2
Subscribe Operation
Add callback to appropriate event array, return unsubscriber
3
Emit Operation
Lookup event O(1), execute all callbacks in order
4
Unsubscribe Operation
Remove specific callback from event array
Key Takeaway
๐ŸŽฏ Key Insight: Hash maps provide instant event lookup while arrays maintain callback order, making this the perfect data structure for event systems!
Asked in
Meta 35 Google 28 Microsoft 22 Amazon 18
42.3K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen