
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 contains a subscribe method to add event listeners to a dictionary, with event names as keys and arrays of callbacks as values. The emit method retrieves the listener list for a given event and executes each callback with provided arguments, returning an array of results. The unsubscribe feature is implemented by removing a callback from the array using an index.
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 def __init__(self, callback):
3 self.callback = callback
4
5 def notify(self, args):
6 return self.callback(*args)
7
8class EventEmitter:
9 def __init__(self):
10 self.observers = {}
11
12 def subscribe(self, event, callback):
13 observer = Observer(callback)
14 if event not in self.observers:
15 self.observers[event] = []
16 self.observers[event].append(observer)
17
18 def unsubscribe():
19 self.observers[event] = [o for o in self.observers[event] if o != observer]
20
21 return type('Subscription', (object,), {'unsubscribe': unsubscribe})()
22
23 def emit(self, event, args=[]):
24 if event in self.observers:
25 return [observer.notify(args) for observer in self.observers[event]]
26 return []The Python solution uses the same Observer pattern concept, where Observer classes act as listeners with a method to execute their logic. The EventEmitter keeps track of observers per event, using them to notify observed changes.