-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
Copy pathreduce.js
37 lines (35 loc) · 1.62 KB
/
reduce.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
define(['../internal/arrayReduce', '../internal/baseCallback', '../internal/baseEach', '../internal/baseReduce', '../lang/isArray'], function(arrayReduce, baseCallback, baseEach, baseReduce, isArray) {
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` through `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not provided the first element of `collection` is used as the initial
* value. The `iteratee` is bound to `thisArg`and invoked with four arguments;
* (accumulator, value, index|key, collection).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {*} [thisArg] The `this` binding of `iteratee`.
* @returns {*} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(sum, n) { return sum + n; });
* // => 6
*
* var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, n, key) {
* result[key] = n * 3;
* return result;
* }, {});
* // => { 'a': 3, 'b': 6, 'c': 9 } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator, thisArg) {
var func = isArray(collection) ? arrayReduce : baseReduce;
return func(collection, baseCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEach);
}
return reduce;
});