Sobes.tech
Middle+

/* * Implement an EventEmitter. * With methods emit and on. * * on(eventName: string | Symbol, callback: (payload?: any) => void): * () => void; * Takes an event name and a callback function. * The function subscribes to the event. * The result of the function should be an unsubscribe function. * * emit(eventName: string | Symbol, payload?: any): void * Takes an event name and a payload that will * be passed to each listener of eventName; the function triggers the event. * If no listener is found, it should throw an exception. * * ------------------------------------------------------ * * Example: * const myEmitter = new EventEmitter(); * * const unSubscribe = myEmitter.on('event', (payload) => { * console.log('an event occurred!!!', payload); */

sobes.tech AI

Answer from AI

typescript class EventEmitter { private events: Map<string | Symbol, Set<(payload?: any) => void>> = new Map();

on(eventName: string | Symbol, callback: (payload?: any) => void): () => void { if (!this.events.has(eventName)) { this.events.set(eventName, new Set()); } const listeners = this.events.get(eventName)!; listeners.add(callback);

// Return unsubscribe function
return () => {
  listeners.delete(callback);
  if (listeners.size === 0) {
    this.events.delete(eventName);
  }
};

}

emit(eventName: string | Symbol, payload?: any): void { const listeners = this.events.get(eventName); if (!listeners || listeners.size === 0) { throw new Error(No listeners for event: ${String(eventName)}); } for (const listener of listeners) { listener(payload); } } }

// Usage example: const myEmitter = new EventEmitter();

const unSubscribe = myEmitter.on('event', (payload) => { console.log('an event occurred!!!', payload); });

myEmitter.emit('event', { data: 123 });

unSubscribe();

// After unsubscribe, calling emit will throw an error // myEmitter.emit('event');


In this solution:
- Uses `Map` to store sets of listeners by event name.
- The `on` method adds a listener and returns an unsubscribe function.
- The `emit` method calls all listeners for an event if they exist, otherwise throws an error.
/* * Implement an EventEmitter. * With methods emit… - sobes.tech