![JAR search and dependency download from the Maven repository](/logo.png)
g2601_2700.s2694_event_emitter.solution.ts Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
// #Medium #2023_07_29_Time_45_ms_(99.58%)_Space_44.6_MB_(72.08%)
type Callback = (...args: any[]) => any
type Subscription = {
unsubscribe: () => void
}
class EventEmitter {
subs: Record = {}
subscribe(eventName: string, callback: Callback): Subscription {
if (!this.subs[eventName]) this.subs[eventName] = []
const idx = this.subs[eventName].push(callback) - 1
return {
unsubscribe: () => this.subs[eventName].splice(idx, 1),
}
}
emit(eventName: string, args: any[] = []): any[] {
return this.subs[eventName]?.map((callback) => callback(...args)) || []
}
}
/*
* const emitter = new EventEmitter();
*
* // Subscribe to the onClick event with onClickCallback
* function onClickCallback() { return 99 }
* const sub = emitter.subscribe('onClick', onClickCallback);
*
* emitter.emit('onClick'); // [99]
* sub.unsubscribe(); // undefined
* emitter.emit('onClick'); // []
*/
export { EventEmitter }
© 2015 - 2025 Weber Informatics LLC | Privacy Policy