* 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 t
(collection, callback, accumulator, thisArg)
| 38853 | * // => { 'a': 3, 'b': 6, 'c': 9 } |
| 38854 | */ |
| 38855 | function reduce(collection, callback, accumulator, thisArg) { |
| 38856 | if (!collection) return accumulator; |
| 38857 | var noaccum = arguments.length < 3; |
| 38858 | callback = lodash.createCallback(callback, thisArg, 4); |
| 38859 | |
| 38860 | var index = -1, |
| 38861 | length = collection.length; |
| 38862 | |
| 38863 | if (typeof length == 'number') { |
| 38864 | if (noaccum) { |
| 38865 | accumulator = collection[++index]; |
| 38866 | } |
| 38867 | while (++index < length) { |
| 38868 | accumulator = callback(accumulator, collection[index], index, collection); |
| 38869 | } |
| 38870 | } else { |
| 38871 | forOwn(collection, function(value, index, collection) { |
| 38872 | accumulator = noaccum |
| 38873 | ? (noaccum = false, value) |
| 38874 | : callback(accumulator, value, index, collection) |
| 38875 | }); |
| 38876 | } |
| 38877 | return accumulator; |
| 38878 | } |
| 38879 | |
| 38880 | /** |
| 38881 | * This method is like `_.reduce` except that it iterates over elements |