All files / src emitter.ts

100% Statements 178/178
100% Branches 52/52
100% Functions 15/15
100% Lines 178/178

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 1791x 1x 1x 1x 1x 1x 1x 1x 1x 1x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 236x 11x 11x 236x 236x 4x 4x 236x 236x 90x 90x 90x 81x 81x 3x 78x 90x 9x 9x 9x 2x 7x 9x 9x 9x 11x 11x 9x 11x 11x 9x 11x 9x 9x 90x 90x 90x 6x 6x 7x 7x 6x 6x 84x 84x 88x 87x 87x 84x 84x 10x 11x 11x 10x 90x 236x 236x 146x 143x 146x 236x 236x 5x 3x 5x 236x 236x 3x 3x 236x 236x 5x 3x 5x 236x 236x 5x 3x 5x 236x 236x 15x 13x 13x 13x 15x 236x 236x 236x 236x 236x 236x 165x 165x 165x 54x 54x 54x 165x 10x 10x 54x 54x 165x 4x 11x 11x 165x 50x 57x 57x 50x 165x 236x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 236x 236x 236x 236x  
import { Listener, SingleOrMultipleListeners, Emitter } from "./types";
 
// Force coverage update
 
const noop = () => {};
 
/**
 * Class-based emitter implementation for better V8 optimization.
 * All instances share methods via prototype.
 */
class EmitterImpl<T = void> implements Emitter<T> {
  /** Set of registered listeners */
  private _listeners: Set<Listener<T>>;
  /** Settled payload (if settled) */
  private _settledPayload: T | undefined = undefined;
  /** Whether the emitter has been settled */
  private _isSettled = false;
 
  constructor(initialListeners?: Listener<T>[]) {
    this._listeners = new Set<Listener<T>>(initialListeners);
    // Bind 'on' to preserve 'this' context when passed as callback
  }
 
  size = (): number => {
    return this._listeners.size;
  };
 
  settled = (): boolean => {
    return this._isSettled;
  };
 
  on = (listenersOrMap: any, mappedListeners?: any): VoidFunction => {
    let newListeners: Listener<T>[];
 
    if (mappedListeners === undefined) {
      // Simple form: on(listeners)
      newListeners = Array.isArray(listenersOrMap)
        ? listenersOrMap
        : [listenersOrMap];
    } else {
      // Mapped form: on(map, listeners)
      const map = listenersOrMap as (value: T) => { value: any } | undefined;
      const sourceListeners: Listener<any>[] = Array.isArray(mappedListeners)
        ? mappedListeners
        : [mappedListeners];
 
      newListeners = [
        (value: T) => {
          const mappedValue = map(value);
          if (mappedValue) {
            for (let i = 0; i < sourceListeners.length; i++) {
              sourceListeners[i]!(mappedValue.value);
            }
          }
        },
      ];
    }
 
    // If settled, call listeners immediately and return no-op
    if (this._isSettled) {
      const payload = this._settledPayload as T;
      for (let i = 0; i < newListeners.length; i++) {
        newListeners[i]!(payload);
      }
      return noop;
    }
 
    const listeners = this._listeners;
    for (let i = 0; i < newListeners.length; i++) {
      listeners.add(newListeners[i]!);
    }
 
    return () => {
      for (let i = 0; i < newListeners.length; i++) {
        listeners.delete(newListeners[i]!);
      }
    };
  };
 
  emit = (payload: T): void => {
    if (this._isSettled) return;
    this._doEmit(payload, false, false);
  };
 
  emitLifo = (payload: T): void => {
    if (this._isSettled) return;
    this._doEmit(payload, false, true);
  };
 
  clear = (): void => {
    this._listeners.clear();
  };
 
  emitAndClear = (payload: T): void => {
    if (this._isSettled) return;
    this._doEmit(payload, true, false);
  };
 
  emitAndClearLifo = (payload: T): void => {
    if (this._isSettled) return;
    this._doEmit(payload, true, true);
  };
 
  settle = (payload: T): void => {
    if (this._isSettled) return;
    this._settledPayload = payload;
    this._isSettled = true;
    this._doEmit(payload, true, false);
  };
 
  /**
   * Internal emit implementation.
   * Creates snapshot to handle modifications during iteration.
   */
  private _doEmit = (payload: T, clear: boolean, lifo: boolean): void => {
    const listeners = this._listeners;
    const size = listeners.size;
    if (size === 0) return;
 
    // Create snapshot - necessary because Set.forEach includes items added during iteration
    const copy = Array.from(listeners);
    if (clear) {
      listeners.clear();
    }
 
    // Use traditional for loop for maximum performance
    if (lifo) {
      for (let i = size - 1; i >= 0; i--) {
        copy[i]!(payload);
      }
    } else {
      for (let i = 0; i < size; i++) {
        copy[i]!(payload);
      }
    }
  };
}
 
/**
 * Creates an event emitter for managing and notifying listeners.
 *
 * An emitter provides a simple pub/sub pattern for managing event listeners.
 * It's used internally by signals and effects to manage subscriptions and notifications.
 *
 * Features:
 * - Add listeners that will be notified when events are emitted
 * - Emit events to all registered listeners
 * - Remove listeners via unsubscribe functions
 * - Clear all listeners at once
 * - Safe to call unsubscribe multiple times (idempotent)
 *
 * @template T - The type of payload that will be emitted to listeners (defaults to void)
 * @returns An emitter object with add, emit, and clear methods
 *
 * @example
 * ```ts
 * const eventEmitter = emitter<string>();
 *
 * // Subscribe to events
 * const unsubscribe = eventEmitter.on((message) => {
 *   console.log('Received:', message);
 * });
 *
 * // Emit an event
 * eventEmitter.emit('Hello'); // Logs: "Received: Hello"
 *
 * // Unsubscribe
 * unsubscribe();
 *
 * // Clear all listeners
 * eventEmitter.clear();
 * ```
 */
export function emitter<T = void>(
  initialListeners?: Listener<T>[]
): Emitter<T> {
  return new EmitterImpl<T>(initialListeners);
}