2694. Event Emitter
https://leetcode.com/problems/event-emitter/
Javascript
class EventEmitter {
subscribed = {}
subscribe(event, cb) {
if (!this.subscribed.hasOwnProperty(event)) {
this.subscribed[event] = []
}
this.subscribed[event].push(cb)
return {
unsubscribe: () => {
if (this.subscribed[event] && this.subscribed[event].length > 1) {
this.subscribed[event].pop()
} else {
delete this.subscribed[event]
}
}
};
}
emit(event, args = []) {
if (this.subscribed.hasOwnProperty(event)) {
return this.subscribed[event].map(callback => callback(...args))
}
return []
}
}