
Sponsored
Sponsored
This approach uses a HashMap (or similar data structure) to maintain a list of listeners (callbacks) for each event. When an event is emitted, we iterate through the list of registered callbacks and invoke them. This list enables easy addition and removal of callbacks (for unsubscribe functionality) and supports ordered invocation on event emission.
Time Complexity: O(n) for emit, where n is the number of callbacks for the event. O(1) for subscribe and unsubscribe.
Space Complexity: O(m), where m is the number of events and subscribed callbacks.
The EventEmitter class in Python leverages a dictionary (or dict) to store event names and corresponding callbacks. The subscribe method adds callbacks to the list for each event, and returns an object with an unsubscribe method. The emit method checks for event listeners and executes them with the given arguments.
This approach employs the Observer pattern, common in design paradigms where a subject maintains a list of observers that react to state changes or events. In this context, the EventEmitter represents the Subject, and listeners are Observers.
Time Complexity: O(n) for notifying listeners (n is the number of listeners).
Space Complexity: O(m), where m consists of stored observers.
1class Observer {
2 constructor(callback) {
3 this.callback = callback;
4 }
5
6 notify(args) {
7 return this.callback(...args);
8 }
9}
10
11class EventEmitter {
12 constructor() {
13 this.observers = {};
14 }
15
16 subscribe(event, callback) {
17 const observer = new Observer(callback);
18 if (!this.observers[event]) this.observers[event] = [];
19 this.observers[event].push(observer);
20
21 return {
22 unsubscribe: () => {
23 this.observers[event] = this.observers[event].filter(obs => obs !== observer);
24 }
25 };
26 }
27
28 emit(event, args = []) {
29 if (!this.observers[event]) return [];
30 return this.observers[event].map(observer => observer.notify(args));
31 }
32}In this JavaScript solution, the Observer class holds the callback function. The notify method executes the callback. EventEmitter manages observers, allowing subscriptions by creating Observer instances and using their notify methods in emit calls.