UNPKG

@daisugi/nekobasu

Version:

Nekobasu is a lightweight, easy to use, asynchronous and efficient EventBus implementation.

58 lines 1.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Nekobasu = void 0; /** * Multicast * * Glossary: * subscription sub */ class Nekobasu { #subCount = 0; #subs = []; subscribe(topicWildcard, eventHandler) { this.#subCount += 1; this.#subs.push({ subId: this.#subCount, topicRe: Nekobasu.#topicWildcardToRe(topicWildcard), topicWildcard, eventHandler, }); return this.#subCount; } async dispatch(topicName, eventArgs) { const subs = this.#subs.filter((sub) => sub.topicRe.test(topicName)); const event = { topicName, payload: eventArgs, mut: {}, }; if (subs) { await Promise.all(subs.map((sub) => sub.eventHandler(event))); } return event; } unsubscribe(subId) { this.#subs = this.#subs.filter((sub) => sub.subId !== subId); } list() { return this.#subs; } /** * Creates a RegExp from the given string, converting asterisks to .* expressions, and escaping all other characters. */ static #topicWildcardToRe(topicWildcard) { return new RegExp(`^${topicWildcard .split('*') .map(Nekobasu.#reEscape) .join('.*')}$`); } /** * RegExp-escapes all characters in the given string. */ static #reEscape(topicWildcardPart) { return topicWildcardPart.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); } } exports.Nekobasu = Nekobasu; //# sourceMappingURL=nekobasu.js.map