The Wayback Machine - https://web.archive.org/web/20170626182521/https://github.com/lodash/lodash/blob/master/reduce.js
Skip to content
Permalink
6cb3460 Feb 6, 2017
@jdalton @bertyhell
45 lines (42 sloc) 1.62 KB
import arrayReduce from './.internal/arrayReduce.js'
import baseEach from './.internal/baseEach.js'
import baseReduce from './.internal/baseReduce.js'
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `reduce`, `reduceRight`, and `transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see reduceRight, transform
* @example
*
* reduce([1, 2], (sum, n) => sum + n, 0)
* // => 3
*
* reduce({ 'a': 1, 'b': 2, 'c': 1 }, (result, value, key) => {
* (result[value] || (result[value] = [])).push(key)
* return result
* }, {})
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
const func = Array.isArray(collection) ? arrayReduce : baseReduce
const initAccum = arguments.length < 3
return func(collection, iteratee, accumulator, initAccum, baseEach)
}
export default reduce
You can't perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Morty Proxy This is a proxified and sanitized view of the page, visit original site.