All files createRace.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 2/2
100% Lines 12/12

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  1x 1x                                                     1x 3x 3x 6x 2x 4x 4x 4x    
/**
 * Constructs a function that will only invoke the first function passed to it
 * concurrently. Once the function has been executed, the racer will be reset
 * and the next invocation will be allowed to execute.
 *
 * Example:
 *
 * ```ts
 * import {createRace} from 'thingies/es2020/createRace';
 *
 * const race = createRace();
 *
 * race(() => {
 *   race(() => {
 *    console.log('This will not be executed');
 *   });
 *   console.log('This will be executed');
 * });
 *
 * race(() => {
 *  console.log('This will be executed');
 * });
 * ```
 *
 * @returns A "race" function that will only invoke the first function passed to it.
 */
export const createRace = () => {
  let invoked: boolean = false;
  return <T>(fn: () => T): T | undefined => {
    if (invoked) return;
    invoked = true;
    try {
      return fn();
    } finally {
      invoked = false;
    }
  };
};