
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.
#include <vector>
#include <unordered_map>
#include <functional>
class EventEmitter {
public:
using Callback = std::function<void()>;
using CallbackList = std::vector<Callback>;
void subscribe(const std::string& event, Callback cb) {
events[event].push_back(cb);
}
void emit(const std::string& event) {
if (events.find(event) != events.end()) {
for (const auto& cb : events[event]) {
cb();
}
}
}
private:
std::unordered_map<std::string, CallbackList> events;
};The C++ version uses an unordered_map to map event names to vectors of std::function objects. The subscribe method adds a callback to the vector corresponding to an event. The emit method iterates over the registered callbacks and invokes them. While unsubscribe functionality is omitted here for brevity, it can be achieved through additional tracking or a channel object.
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.