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 - Hash Map with Arrays INPUT Operations Array: [0] 'subscribe' eventName: 'click' callback: () => 1 [1] 'emit' eventName: 'click' EventEmitter Class: class EventEmitter { events = new Map() } HashMap Array Fn ALGORITHM STEPS 1 Initialize HashMap Create events Map() 2 Subscribe 'click' Add callback to array events.get('click'): [() => 1] 3 Emit 'click' Get listeners for event 4 Execute Callbacks Call each fn, collect results () => 1 --> returns 1 results = [1] FINAL RESULT Final Events Map State: Map { 'click' => [() => 1] } Emit 'click' Result: [1] Output: [[1]] OK Key Insight: The EventEmitter uses a HashMap where keys are event names and values are arrays of callbacks. This enables O(1) lookup for events and O(n) iteration through listeners in subscription order. The unsubscribe pattern returns closure over the specific callback for easy removal. TutorialsPoint - Event Emitter | Hash Map with Arrays Approach
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