| /** |
| * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> |
| * Build: `lodash modularize underscore exports="node" -o ./underscore/` |
| * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> |
| * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> |
| * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors |
| * Available under MIT license <http://lodash.com/license> |
| */ |
| var createCallback = require('../functions/createCallback'), |
| forOwn = require('../objects/forOwn'); |
| |
| /** |
| * Reduces a collection to a value which is the accumulated result of running |
| * each element in the collection through the callback, where each successive |
| * callback execution consumes the return value of the previous execution. If |
| * `accumulator` is not provided the first element of the collection will be |
| * used as the initial `accumulator` value. The callback is bound to `thisArg` |
| * and invoked with four arguments; (accumulator, value, index|key, collection). |
| * |
| * @static |
| * @memberOf _ |
| * @alias foldl, inject |
| * @category Collections |
| * @param {Array|Object|string} collection The collection to iterate over. |
| * @param {Function} [callback=identity] The function called per iteration. |
| * @param {*} [accumulator] Initial value of the accumulator. |
| * @param {*} [thisArg] The `this` binding of `callback`. |
| * @returns {*} Returns the accumulated value. |
| * @example |
| * |
| * var sum = _.reduce([1, 2, 3], function(sum, num) { |
| * return sum + num; |
| * }); |
| * // => 6 |
| * |
| * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { |
| * result[key] = num * 3; |
| * return result; |
| * }, {}); |
| * // => { 'a': 3, 'b': 6, 'c': 9 } |
| */ |
| function reduce(collection, callback, accumulator, thisArg) { |
| if (!collection) return accumulator; |
| var noaccum = arguments.length < 3; |
| callback = createCallback(callback, thisArg, 4); |
| |
| var index = -1, |
| length = collection.length; |
| |
| if (typeof length == 'number') { |
| if (noaccum) { |
| accumulator = collection[++index]; |
| } |
| while (++index < length) { |
| accumulator = callback(accumulator, collection[index], index, collection); |
| } |
| } else { |
| forOwn(collection, function(value, index, collection) { |
| accumulator = noaccum |
| ? (noaccum = false, value) |
| : callback(accumulator, value, index, collection) |
| }); |
| } |
| return accumulator; |
| } |
| |
| module.exports = reduce; |