您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

forEachBail.js 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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) => { // eslint-disable-line
  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(array, iterator, callback) {
  35. if(array.length === 0) return callback();
  36. let currentPos = array.length;
  37. let currentResult;
  38. let done = [];
  39. for(let i = 0; i < array.length; i++) {
  40. const itCb = createIteratorCallback(i);
  41. iterator(array[i], i, itCb);
  42. if(currentPos === 0) break;
  43. }
  44. function createIteratorCallback(i) {
  45. return(...args) => { // eslint-disable-line
  46. if(i >= currentPos) return; // ignore
  47. done.push(i);
  48. if(args.length > 0) {
  49. currentPos = i + 1;
  50. done = done.filter(item => {
  51. return item <= i;
  52. });
  53. currentResult = args;
  54. }
  55. if(done.length === currentPos) {
  56. callback.apply(null, currentResult);
  57. currentPos = 0;
  58. }
  59. };
  60. }
  61. };