Medium
This question is a daily question and will count towards your daily streak.
Your team is troubleshooting a memory leak in a long-running application. Hidden in this event subscription module is a common mistake that can lead to memory leaks. Can you spot the issue?
1class EventManager {2 constructor() {3 this.subscribers = new WeakMap();4 this.eventHistory = [];5 }67 subscribe(subscriber, eventType, callback) {8 if (!this.subscribers.has(subscriber)) {9 this.subscribers.set(subscriber, new Map());10 }1112 const subscriberEvents = this.subscribers.get(subscriber);13 if (!subscriberEvents.has(eventType)) {14 subscriberEvents.set(eventType, new Set());15 }1617 subscriberEvents.get(eventType).add(callback);1819 // Keep track of subscription history20 this.eventHistory.push({21 subscriber,22 eventType,23 timestamp: new Date()24 });25 }2627 emit(eventType, data) {28 for (let [subscriber, events] of this.subscribers) {29 const callbacks = events.get(eventType);30 if (callbacks) {31 callbacks.forEach(callback => callback(data));32 }33 }34 }3536 unsubscribe(subscriber, eventType) {37 const subscriberEvents = this.subscribers.get(subscriber);38 if (subscriberEvents) {39 subscriberEvents.delete(eventType);40 }41 }42}