createRace.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createRace = void 0;
  4. /**
  5. * Constructs a function that will only invoke the first function passed to it
  6. * concurrently. Once the function has been executed, the racer will be reset
  7. * and the next invocation will be allowed to execute.
  8. *
  9. * Example:
  10. *
  11. * ```ts
  12. * import {createRace} from 'thingies/es2020/createRace';
  13. *
  14. * const race = createRace();
  15. *
  16. * race(() => {
  17. * race(() => {
  18. * console.log('This will not be executed');
  19. * });
  20. * console.log('This will be executed');
  21. * });
  22. *
  23. * race(() => {
  24. * console.log('This will be executed');
  25. * });
  26. * ```
  27. *
  28. * @returns A "race" function that will only invoke the first function passed to it.
  29. */
  30. const createRace = () => {
  31. let invoked = false;
  32. return (fn) => {
  33. if (invoked)
  34. return;
  35. invoked = true;
  36. try {
  37. return fn();
  38. }
  39. finally {
  40. invoked = false;
  41. }
  42. };
  43. };
  44. exports.createRace = createRace;