forEachBail.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. module.exports = function forEachBail(array, iterator, callback) {
  7. if (array.length === 0) return callback();
  8. let currentPos = array.length;
  9. let currentResult;
  10. let done = [];
  11. for (let i = 0; i < array.length; i++) {
  12. const itCb = createIteratorCallback(i);
  13. iterator(array[i], itCb);
  14. if (currentPos === 0) break;
  15. }
  16. function createIteratorCallback(i) {
  17. return (...args) => {
  18. if (i >= currentPos) return; // ignore
  19. done.push(i);
  20. if (args.length > 0) {
  21. currentPos = i + 1;
  22. done = done.filter(item => {
  23. return item <= i;
  24. });
  25. currentResult = args;
  26. }
  27. if (done.length === currentPos) {
  28. callback.apply(null, currentResult);
  29. currentPos = 0;
  30. }
  31. };
  32. }
  33. };
  34. module.exports.withIndex = function forEachBailWithIndex(
  35. array,
  36. iterator,
  37. callback
  38. ) {
  39. if (array.length === 0) return callback();
  40. let currentPos = array.length;
  41. let currentResult;
  42. let done = [];
  43. for (let i = 0; i < array.length; i++) {
  44. const itCb = createIteratorCallback(i);
  45. iterator(array[i], i, itCb);
  46. if (currentPos === 0) break;
  47. }
  48. function createIteratorCallback(i) {
  49. return (...args) => {
  50. if (i >= currentPos) return; // ignore
  51. done.push(i);
  52. if (args.length > 0) {
  53. currentPos = i + 1;
  54. done = done.filter(item => {
  55. return item <= i;
  56. });
  57. currentResult = args;
  58. }
  59. if (done.length === currentPos) {
  60. callback.apply(null, currentResult);
  61. currentPos = 0;
  62. }
  63. };
  64. }
  65. };