bitburner-src/src/utils/EventEmitter.ts

50 lines
1.1 KiB
TypeScript
Raw Normal View History

/**
* Generic Event Emitter class following a subscribe/publish paradigm.
*/
import { IMap } from "../types";
type cbFn = (...args: any[]) => any;
export interface ISubscriber {
2021-09-05 01:09:30 +02:00
/**
* Callback function that will be run when an event is emitted
*/
cb: cbFn;
/**
* Name/identifier for this subscriber
*/
id: string;
}
2021-09-18 21:44:39 +02:00
function uuidv4(): string {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
2021-09-05 01:09:30 +02:00
2021-09-18 21:44:39 +02:00
export class EventEmitter<T extends any[]> {
subscribers: { [key: string]: (...args: [...T]) => void | undefined } = {};
subscribe(s: (...args: [...T]) => void): () => void {
let uuid = uuidv4();
while (this.subscribers[uuid] !== undefined) uuid = uuidv4();
this.subscribers[uuid] = s;
2021-09-18 21:44:39 +02:00
return () => {
delete this.subscribers[uuid];
};
2021-09-05 01:09:30 +02:00
}
2021-09-18 21:44:39 +02:00
emit(...args: [...T]): void {
2021-09-05 01:09:30 +02:00
for (const s in this.subscribers) {
const sub = this.subscribers[s];
2021-09-18 21:44:39 +02:00
if (sub === undefined) continue;
2021-09-18 21:44:39 +02:00
sub(...args);
}
2021-09-05 01:09:30 +02:00
}
}