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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code