All files / core/src stack.ts

100% Statements 20/20
100% Branches 3/3
100% Functions 3/3
100% Lines 20/20

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  1x   1x             1x 11x 11x 11x 11x 11x                   1x 14x 14x   14x 14x 14x 14x 14x 14x             1x 1x 1x  
import type { RefStack } from './types.js';
import { closure } from './utils/index.js';
 
export const STACK_SYMBOL = Symbol('call-stack');
 
/**
 * Creates a new reference stack scope for managing reactive references.
 *
 * @returns A new RefStack object with initialized index and empty states map
 */
export function createStack(): RefStack {
  return {
    index: 0,
    states: new Map(),
  };
}
 
/**
 * Executes a function within a specific reference stack context.
 *
 * @template T - The return type of the executed function
 * @param scope - The reference scope to use during execution
 * @param fn - The function to execute within the given scope
 * @returns The result of the executed function
 */
export function withStack<T>(scope: RefStack, fn: () => T) {
  const prevStack = closure.get<RefStack>(STACK_SYMBOL);
  closure.set(STACK_SYMBOL, scope);
 
  try {
    return fn();
  } finally {
    closure.set(STACK_SYMBOL, prevStack);
  }
}
 
/**
 * Retrieves the current reference stack context.
 *
 * @returns The current RefStack if one exists, undefined otherwise
 */
export function getCurrentStack() {
  return closure.get<RefStack>(STACK_SYMBOL);
}