forEachBail.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  7. /**
  8. * @template T
  9. * @template Z
  10. * @callback Iterator
  11. * @param {T} item item
  12. * @param {(err?: null|Error, result?: null|Z) => void} callback callback
  13. * @param {number} i index
  14. * @returns {void}
  15. */
  16. /**
  17. * @template T
  18. * @template Z
  19. * @param {T[]} array array
  20. * @param {Iterator<T, Z>} iterator iterator
  21. * @param {(err?: null|Error, result?: null|Z, i?: number) => void} callback callback after all items are iterated
  22. * @returns {void}
  23. */
  24. module.exports = function forEachBail(array, iterator, callback) {
  25. if (array.length === 0) return callback();
  26. let i = 0;
  27. const next = () => {
  28. /** @type {boolean|undefined} */
  29. let loop = undefined;
  30. iterator(
  31. array[i++],
  32. (err, result) => {
  33. if (err || result !== undefined || i >= array.length) {
  34. return callback(err, result, i);
  35. }
  36. if (loop === false) while (next());
  37. loop = true;
  38. },
  39. i
  40. );
  41. if (!loop) loop = false;
  42. return loop;
  43. };
  44. while (next());
  45. };