All files / json-type/src/codegen util.ts

84.21% Statements 16/19
66.66% Branches 2/3
75% Functions 3/4
81.25% Lines 13/16

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 3918x                             18x               45x 45x 13251x 13251x 13251x 13251x 1903x 72882x 1900x 1900x   72882x        
export const normalizeAccessor = (key: string): string => {
  // Simple property access for valid identifiers, bracket notation otherwise
  Iif (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)) {
    return `.${key}`;
  }
  return `[${JSON.stringify(key)}]`;
};
 
/**
 * Creates a lazily evaluated factory function that caches results based on the
 * first argument.
 *
 * @param factory A factory function that takes a key as the first argument,
 *     potentially more arguments, and returns a function.
 */
export const lazyKeyedFactory = <
  K extends WeakKey,
  FactoryThis,
  FactoryArgs extends [key: K, ...args: any[]],
  Method extends (...args: any[]) => any,
>(
  factory: (this: FactoryThis, ...args: FactoryArgs) => Method,
) => {
  const cache = new WeakMap<K, Method>();
  return function (this: FactoryThis, ...factoryArgs: FactoryArgs) {
    const factoryThis = this;
    const key = factoryArgs[0];
    let estimator = cache.get(key);
    if (estimator) return estimator;
    return function (this: any, ...methodArgs: Parameters<Method>) {
      if (!estimator) {
        estimator = factory.call(factoryThis, ...factoryArgs);
        cache.set(key, estimator);
      }
      return estimator.call(this, ...methodArgs);
    } as Method;
  };
};