enh(utils) refactor emitter to use Map and Set; update logging mechanism
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
class Emitter {
|
||||
#listeners;
|
||||
constructor() {
|
||||
this.#listeners = {};
|
||||
this.#listeners = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -11,10 +11,10 @@ class Emitter {
|
||||
* @param {Function} callback - The callback function to be executed when the event is triggered.
|
||||
*/
|
||||
on(event, callback) {
|
||||
if (!this.#listeners[event]) {
|
||||
this.#listeners[event] = [];
|
||||
if (!this.#listeners.has(event)) {
|
||||
this.#listeners.set(event, new Set());
|
||||
}
|
||||
this.#listeners[event].push(callback);
|
||||
this.#listeners.get(event).push(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,28 +25,15 @@ class Emitter {
|
||||
* @param {Function} [callback] - The callback function to be removed.
|
||||
*/
|
||||
off(event, callback = undefined) {
|
||||
if (typeof event != 'string') {
|
||||
throw new TypeError('event must be a string');
|
||||
return;
|
||||
if (typeof event != 'string') return;
|
||||
|
||||
if (!this.#listeners.has(event)) return false;
|
||||
|
||||
if (!callback || this.#listeners.get(event).size === 0) {
|
||||
return this.#listeners.delete(event);
|
||||
}
|
||||
|
||||
if (
|
||||
!Array.isArray(this.#listeners[event]) ||
|
||||
this.#listeners[event].length === 0
|
||||
) {
|
||||
throw new TypeError(
|
||||
`listener for \`${event}\` is not an array or empty`
|
||||
);
|
||||
}
|
||||
|
||||
if (!callback) {
|
||||
this.#listeners[event] = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
this.#listeners[event] = this.#listeners[event].filter(
|
||||
(listener) => listener !== callback
|
||||
);
|
||||
this.#listeners.get(event).delete(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,11 +43,11 @@ class Emitter {
|
||||
* @param {...any} args - The arguments to pass to the event listeners.
|
||||
*/
|
||||
emit(event, ...args) {
|
||||
if (!this.#listeners[event]) {
|
||||
if (!this.#listeners.has(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const callback of this.#listeners[event]) {
|
||||
for (const callback of [...this.#listeners.get(event)]) {
|
||||
callback(this, ...args);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user