Skip to content

Commit

Permalink
refactor(eventemmiter.ts): implement Subscriptions class by extending…
Browse files Browse the repository at this point in the history
… Map

Implement Subscriptions class by Extending Map to get a type-safe get() method and simplify the code
of EventEmitter.
  • Loading branch information
bencelaszlo committed Sep 25, 2024
1 parent ba1b595 commit ab9bcbc
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions src/EventEmitter.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
export type EventCallback<T = void> = (...args: Array<any>) => T;
export type Subscriptions = Map<

export class Subscriptions extends Map<
string,
Array<{ id: symbol; callback: EventCallback }>
>;
> {
get(key: string): { id: symbol; callback: EventCallback }[] {
return super.get(key) || [];
}
}

export type Unsubscribe = () => void;

export class EventEmitter {
subscriptions: Subscriptions;

constructor() {
this.subscriptions = new Map();
this.subscriptions = new Subscriptions();
}

/**
Expand All @@ -19,19 +25,17 @@ export class EventEmitter {
*/
subscribe(eventName: string, callback: EventCallback): Unsubscribe {
const id = Symbol(callback.toString());
this.subscriptions.set(
eventName,
this.subscriptions.has(eventName)
? [...(this.subscriptions.get(eventName) || []), { id, callback }]
: [{ id, callback }]
);
this.subscriptions.set(eventName, [
...this.subscriptions.get(eventName),
{ id, callback },
]);

return () =>
this.subscriptions.set(
eventName,
(this.subscriptions.get(eventName) || []).filter(
({ id: subscriptionId }) => subscriptionId !== id
)
this.subscriptions
.get(eventName)
.filter(({ id: subscriptionId }) => subscriptionId !== id)
);
}

Expand All @@ -40,8 +44,8 @@ export class EventEmitter {
* @param {Array<any>} args
*/
emit(eventName: string, ...args: Array<any>): void {
(this.subscriptions.get(eventName) || []).forEach(({ callback }) =>
callback(...args)
);
this.subscriptions
.get(eventName)
.forEach(({ callback }) => callback(...args));
}
}

0 comments on commit ab9bcbc

Please sign in to comment.