eachOfLimit.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _once = require('./once.js');
  6. var _once2 = _interopRequireDefault(_once);
  7. var _iterator = require('./iterator.js');
  8. var _iterator2 = _interopRequireDefault(_iterator);
  9. var _onlyOnce = require('./onlyOnce.js');
  10. var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
  11. var _wrapAsync = require('./wrapAsync.js');
  12. var _asyncEachOfLimit = require('./asyncEachOfLimit.js');
  13. var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit);
  14. var _breakLoop = require('./breakLoop.js');
  15. var _breakLoop2 = _interopRequireDefault(_breakLoop);
  16. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  17. exports.default = limit => {
  18. return (obj, iteratee, callback) => {
  19. callback = (0, _once2.default)(callback);
  20. if (limit <= 0) {
  21. throw new RangeError('concurrency limit cannot be less than 1');
  22. }
  23. if (!obj) {
  24. return callback(null);
  25. }
  26. if ((0, _wrapAsync.isAsyncGenerator)(obj)) {
  27. return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback);
  28. }
  29. if ((0, _wrapAsync.isAsyncIterable)(obj)) {
  30. return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback);
  31. }
  32. var nextElem = (0, _iterator2.default)(obj);
  33. var done = false;
  34. var canceled = false;
  35. var running = 0;
  36. var looping = false;
  37. function iterateeCallback(err, value) {
  38. if (canceled) return;
  39. running -= 1;
  40. if (err) {
  41. done = true;
  42. callback(err);
  43. } else if (err === false) {
  44. done = true;
  45. canceled = true;
  46. } else if (value === _breakLoop2.default || done && running <= 0) {
  47. done = true;
  48. return callback(null);
  49. } else if (!looping) {
  50. replenish();
  51. }
  52. }
  53. function replenish() {
  54. looping = true;
  55. while (running < limit && !done) {
  56. var elem = nextElem();
  57. if (elem === null) {
  58. done = true;
  59. if (running <= 0) {
  60. callback(null);
  61. }
  62. return;
  63. }
  64. running += 1;
  65. iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback));
  66. }
  67. looping = false;
  68. }
  69. replenish();
  70. };
  71. };
  72. module.exports = exports['default'];