Revenge/src/lib/emitter.ts

34 lines
1.1 KiB
TypeScript
Raw Normal View History

import { Emitter, EmitterEvent, EmitterListener, EmitterListenerData, EmitterListeners } from "@types";
2023-02-26 22:56:36 +00:00
export enum Events {
GET = "GET",
SET = "SET",
DEL = "DEL",
};
export default function createEmitter(): Emitter {
2023-02-04 02:28:08 +00:00
return {
listeners: Object.values(Events).reduce<EmitterListeners>((acc, val: string) => ((acc[val] = new Set<EmitterListener>()), acc), {}) as EmitterListeners,
2023-02-04 02:28:08 +00:00
on(event: EmitterEvent, listener: EmitterListener) {
if (!this.listeners[event].has(listener)) this.listeners[event].add(listener);
},
2023-02-04 02:28:08 +00:00
off(event: EmitterEvent, listener: EmitterListener) {
this.listeners[event].delete(listener);
},
2023-02-04 02:28:08 +00:00
once(event: EmitterEvent, listener: EmitterListener) {
const once = (event: EmitterEvent, data: EmitterListenerData) => {
this.off(event, once);
listener(event, data);
};
this.on(event, once);
},
2023-02-04 02:28:08 +00:00
emit(event: EmitterEvent, data: EmitterListenerData) {
for (const listener of this.listeners[event]) listener(event, data);
},
};
}