上次编辑到这里,代码来自缓存 点击恢复默认模板
class EventEmitter {
subscribe(event, cb) {
return {
unsubscribe: () => {
}
};
}
emit(event, 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'); // []
*/
javascript 解法, 执行用时: 80 ms, 内存消耗: 41.6 MB, 提交时间: 2023-05-22 14:29:18
class EventEmitter {
constructor() {
this.ke = {}
}
subscribe(event, cb) {
if(!this.ke[event]) this.ke[event] = []
this.ke[event].push(cb)
return {
unsubscribe: () => {
this.ke[event] = this.ke[event].filter(v => v !== cb)
}
};
}
emit(event, args = []) {
return (this.ke[event] ?? []).map(v => v(...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'); // []
*/
typescript 解法, 执行用时: 60 ms, 内存消耗: 44 MB, 提交时间: 2023-05-22 14:24:39
type Callback = (...args: any[]) => any;
type Subscription = {
unsubscribe: () => void
}
class EventEmitter {
#eventsMap: Map<string, Set<Callback>> = new Map();
subscribe(eventName: string, callback: Callback): Subscription {
this.#eventsMap.set(eventName, (this.#eventsMap.get(eventName)??new Set()).add(callback));
return {
unsubscribe: () => {
this.#eventsMap.get(eventName)?.delete(callback);
}
};
}
emit(eventName: string, args: any[] = []): any {
return [...(this.#eventsMap.get(eventName)??[])].map(fn=>fn?.(...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'); // []
*/
/**
* 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'); // []
*/