groupByLimit.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _mapLimit = require('./mapLimit.js');
  6. var _mapLimit2 = _interopRequireDefault(_mapLimit);
  7. var _wrapAsync = require('./internal/wrapAsync.js');
  8. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  9. var _awaitify = require('./internal/awaitify.js');
  10. var _awaitify2 = _interopRequireDefault(_awaitify);
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. /**
  13. * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
  14. *
  15. * @name groupByLimit
  16. * @static
  17. * @memberOf module:Collections
  18. * @method
  19. * @see [async.groupBy]{@link module:Collections.groupBy}
  20. * @category Collection
  21. * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
  22. * @param {number} limit - The maximum number of async operations at a time.
  23. * @param {AsyncFunction} iteratee - An async function to apply to each item in
  24. * `coll`.
  25. * The iteratee should complete with a `key` to group the value under.
  26. * Invoked with (value, callback).
  27. * @param {Function} [callback] - A callback which is called when all `iteratee`
  28. * functions have finished, or an error occurs. Result is an `Object` whoses
  29. * properties are arrays of values which returned the corresponding key.
  30. * @returns {Promise} a promise, if no callback is passed
  31. */
  32. function groupByLimit(coll, limit, iteratee, callback) {
  33. var _iteratee = (0, _wrapAsync2.default)(iteratee);
  34. return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => {
  35. _iteratee(val, (err, key) => {
  36. if (err) return iterCb(err);
  37. return iterCb(err, { key, val });
  38. });
  39. }, (err, mapResults) => {
  40. var result = {};
  41. // from MDN, handle object having an `hasOwnProperty` prop
  42. var { hasOwnProperty } = Object.prototype;
  43. for (var i = 0; i < mapResults.length; i++) {
  44. if (mapResults[i]) {
  45. var { key } = mapResults[i];
  46. var { val } = mapResults[i];
  47. if (hasOwnProperty.call(result, key)) {
  48. result[key].push(val);
  49. } else {
  50. result[key] = [val];
  51. }
  52. }
  53. }
  54. return callback(err, result);
  55. });
  56. }
  57. exports.default = (0, _awaitify2.default)(groupByLimit, 4);
  58. module.exports = exports['default'];