All files once.ts

100% Statements 10/10
100% Branches 4/4
100% Functions 2/2
100% Lines 10/10

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    1x 1x 1x           5x 17x 17x 4x 17x 5x 17x      
/* tslint:disable no-invalid-this */
 
const instances = new WeakMap<any, WeakMap<any, any>>();
 
/**
 * A class method decorator that limits a method to be called only once. All
 * subsequent calls will return the result of the first call.
 */
export function once<This, Args extends any[], Return>(
  fn: (this: This, ...args: Args) => Return,
  context?: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
  return function (this: This, ...args: Args): Return {
    let map = instances.get(this);
    if (!map) instances.set(this, (map = new WeakMap<any, any>()));
    if (!map.has(fn)) map.set(fn, fn.apply(this, args));
    return map.get(fn);
  };
}