inject.js
1 'use strict'; 2 3 Object.defineProperty(exports, "__esModule", { 4 value: true 5 }); 6 7 var _eachOfSeries = require('./eachOfSeries'); 8 9 var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); 10 11 var _once = require('./internal/once'); 12 13 var _once2 = _interopRequireDefault(_once); 14 15 var _wrapAsync = require('./internal/wrapAsync'); 16 17 var _wrapAsync2 = _interopRequireDefault(_wrapAsync); 18 19 var _awaitify = require('./internal/awaitify'); 20 21 var _awaitify2 = _interopRequireDefault(_awaitify); 22 23 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 24 25 /** 26 * Reduces `coll` into a single value using an async `iteratee` to return each 27 * successive step. `memo` is the initial state of the reduction. This function 28 * only operates in series. 29 * 30 * For performance reasons, it may make sense to split a call to this function 31 * into a parallel map, and then use the normal `Array.prototype.reduce` on the 32 * results. This function is for situations where each step in the reduction 33 * needs to be async; if you can get the data before reducing it, then it's 34 * probably a good idea to do so. 35 * 36 * @name reduce 37 * @static 38 * @memberOf module:Collections 39 * @method 40 * @alias inject 41 * @alias foldl 42 * @category Collection 43 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. 44 * @param {*} memo - The initial state of the reduction. 45 * @param {AsyncFunction} iteratee - A function applied to each item in the 46 * array to produce the next step in the reduction. 47 * The `iteratee` should complete with the next state of the reduction. 48 * If the iteratee complete with an error, the reduction is stopped and the 49 * main `callback` is immediately called with the error. 50 * Invoked with (memo, item, callback). 51 * @param {Function} [callback] - A callback which is called after all the 52 * `iteratee` functions have finished. Result is the reduced value. Invoked with 53 * (err, result). 54 * @returns {Promise} a promise, if no callback is passed 55 * @example 56 * 57 * async.reduce([1,2,3], 0, function(memo, item, callback) { 58 * // pointless async: 59 * process.nextTick(function() { 60 * callback(null, memo + item) 61 * }); 62 * }, function(err, result) { 63 * // result is now equal to the last value of memo, which is 6 64 * }); 65 */ 66 function reduce(coll, memo, iteratee, callback) { 67 callback = (0, _once2.default)(callback); 68 var _iteratee = (0, _wrapAsync2.default)(iteratee); 69 return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => { 70 _iteratee(memo, x, (err, v) => { 71 memo = v; 72 iterCb(err); 73 }); 74 }, err => callback(err, memo)); 75 } 76 exports.default = (0, _awaitify2.default)(reduce, 4); 77 module.exports = exports['default'];