Event Emitter - Problem

Design an EventEmitter class similar to Node.js event system or DOM Event Target interface. The class should allow subscribing to events and emitting them with callback execution.

Your EventEmitter class should have the following methods:

subscribe(eventName, callback): Takes an event name (string) and callback function. Multiple listeners can subscribe to the same event and will be called in subscription order. Returns an object with an unsubscribe method to remove the callback.

emit(eventName, args): Takes an event name (string) and optional array of arguments to pass to callbacks. Returns an array of results from all callback executions in subscription order, or empty array if no listeners exist.

Input & Output

Example 1 — Basic Subscribe and Emit
$ Input: operations = [['subscribe', 'click', '() => 1'], ['emit', 'click']]
Output: [[1]]
💡 Note: Subscribe callback that returns 1 to 'click' event, then emit 'click' which calls the callback and returns [1]
Example 2 — Multiple Callbacks
$ Input: operations = [['subscribe', 'click', '() => 1'], ['subscribe', 'click', '() => 2'], ['emit', 'click']]
Output: [[1, 2]]
💡 Note: Two callbacks subscribed to 'click', emit returns both results in subscription order
Example 3 — Unsubscribe
$ Input: operations = [['subscribe', 'click', '() => 1'], ['unsubscribe', 0], ['emit', 'click']]
Output: [[]]
💡 Note: After unsubscribing the only callback, emit returns empty array

Constraints

  • 1 ≤ operations.length ≤ 100
  • Event names are non-empty strings
  • Callbacks are valid JavaScript functions
  • Arguments passed to emit are valid JSON values

Visualization

Tap to expand
Event Emitter: Subscribe → Emit → Resultssubscribe('click', fn1)Returns unsubscribesubscribe('click', fn2)Multiple listenersEvent Storageclick: [fn1, fn2]hover: [fn3]emit('click', [5])Trigger callbacksExecute in Orderfn1(5) → result1fn2(5) → result2Output: [result1, result2]Callbacks executed in subscription order
Understanding the Visualization
1
Subscribe
Register callbacks for specific events
2
Emit
Trigger all callbacks for an event with arguments
3
Results
Return array of callback results in order
Key Takeaway
🎯 Key Insight: Use hash map to group callbacks by event name for O(1) event lookup and efficient emission
Asked in
Meta 35 Google 28 Microsoft 22 Amazon 18
32.5K Views
Medium Frequency
~25 min Avg. Time
856 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