|
| 1 | +/** |
| 2 | + * 2694. Event Emitter |
| 3 | + * https://leetcode.com/problems/event-emitter/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Design an EventEmitter class. This interface is similar (but with some differences) to the one |
| 7 | + * found in Node.js or the Event Target interface of the DOM. The EventEmitter should allow for |
| 8 | + * subscribing to events and emitting them. |
| 9 | + * |
| 10 | + * Your EventEmitter class should have the following two methods: |
| 11 | + * - subscribe - This method takes in two arguments: the name of an event as a string and a callback |
| 12 | + * function. This callback function will later be called when the event is emitted. |
| 13 | + * An event should be able to have multiple listeners for the same event. When emitting an event |
| 14 | + * with multiple callbacks, each should be called in the order in which they were subscribed. |
| 15 | + * An array of results should be returned. You can assume no callbacks passed to subscribe are |
| 16 | + * referentially identical. |
| 17 | + * The subscribe method should also return an object with an unsubscribe method that enables the |
| 18 | + * user to unsubscribe. When it is called, the callback should be removed from the list of |
| 19 | + * subscriptions and undefined should be returned. |
| 20 | + * - emit - This method takes in two arguments: the name of an event as a string and an optional |
| 21 | + * array of arguments that will be passed to the callback(s). If there are no callbacks subscribed |
| 22 | + * to the given event, return an empty array. Otherwise, return an array of the results of all |
| 23 | + * callback calls in the order they were subscribed. |
| 24 | + */ |
| 25 | + |
| 26 | +class EventEmitter { |
| 27 | + constructor() { |
| 28 | + this.events = new Map(); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * @param {string} eventName |
| 33 | + * @param {Function} callback |
| 34 | + * @return {Object} |
| 35 | + */ |
| 36 | + subscribe(eventName, callback) { |
| 37 | + if (!this.events.has(eventName)) { |
| 38 | + this.events.set(eventName, []); |
| 39 | + } |
| 40 | + |
| 41 | + const listeners = this.events.get(eventName); |
| 42 | + listeners.push(callback); |
| 43 | + |
| 44 | + return { |
| 45 | + unsubscribe: () => { |
| 46 | + const index = listeners.indexOf(callback); |
| 47 | + if (index !== -1) { |
| 48 | + listeners.splice(index, 1); |
| 49 | + } |
| 50 | + } |
| 51 | + }; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * @param {string} eventName |
| 56 | + * @param {Array} args |
| 57 | + * @return {Array} |
| 58 | + */ |
| 59 | + emit(eventName, args = []) { |
| 60 | + if (!this.events.has(eventName)) { |
| 61 | + return []; |
| 62 | + } |
| 63 | + |
| 64 | + return this.events.get(eventName).map(listener => listener(...args)); |
| 65 | + } |
| 66 | +} |
0 commit comments