ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Type-Safe Event Emitter with Listener Management

TypeScript

Goal -- WPM

Ready
Exercise Algorithm Area
1class EventEmitterSimple {
2private listeners: Record<string, Function[]> = {};
3
4on(eventName: string, listener: Function): void {
5if (!this.listeners[eventName]) {
6this.listeners[eventName] = [];
7}
8this.listeners[eventName].push(listener);
9}
10
11emit(eventName: string, payload?: any): void {
12const eventListeners = this.listeners[eventName];
13if (eventListeners) {
14eventListeners.forEach(listener => {
15listener(payload);
16});
17}
18}
19}
Algorithm description viewbox

Type-Safe Event Emitter with Listener Management

Algorithm description:

This simplified `EventEmitter` class allows for basic event handling. It enables components to subscribe to named events using `on` and trigger those events with optional payloads using `emit`. This pattern is fundamental for decoupling different parts of an application, allowing them to communicate without direct dependencies, which is common in event-driven architectures.

Algorithm explanation:

The `EventEmitterSimple` class uses a `Record<string, Function[]>` to store listeners, mapping event names (strings) to arrays of callback functions. The `on` method adds a listener to the array associated with the given `eventName`, creating the array if it doesn't exist. The `emit` method retrieves the array of listeners for a given `eventName` and invokes each listener, passing the `payload` if provided. This implementation is straightforward but lacks the type safety of more advanced versions. The time complexity for `on` is O(1) on average. `emit` is O(m), where m is the number of listeners for an event. Space complexity is O(N), where N is the total number of listeners.

Pseudocode:

class EventEmitterSimple:
  listeners = empty map (string -> list of functions)

  method on(eventName, listener):
    if eventName not in listeners:
      listeners[eventName] = empty list
    add listener to listeners[eventName]

  method emit(eventName, payload):
    if eventName in listeners:
      for each listener in listeners[eventName]:
        call listener with payload