_.reduce(collection, [iteratee=_.identity], [accumulator])
84
_.reduce(collection, [iteratee=_.identity], [accumulator])
_.reduce类似原生的reduce将每一个集合中的元素通过iteratee处理后的结果累加到一个值,每一次连续的调用的累加值都是上一次的返回值。如果初始累加值没有提供,就使用第一次循环的返回值
参数
collection (Array|Object): 需要遍历的集合
[iteratee=_.identity] (Function): 每一次遍历元素调用的方法
[accumulator] (*): 初始累加器值
返回值
(*): 返回累加好的值
例子
_.reduce([1, 2], function(sum, n) { return sum + n; }, 0); // => 3 _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { (result[value] || (result[value] = [])).push(key); return result; }, {}); // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
源代码:
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) */ //将每一个集合中的元素通过iteratee处理后的结果累加到一个值,每一次连续的调用的累加值都是上一次的返回值。如果初始累加值没有提供,就使用第一次循环的返回值 function reduce(collection, iteratee, accumulator) { const func = Array.isArray(collection) ? arrayReduce : baseReduce//判断collection参数是数组还是其他类型,如果是数组调用arrayReduce,否则baseReduce const initAccum = arguments.length < 3 return func(collection, iteratee, accumulator, initAccum, baseEach) } export default reduce
arrayReduce
/** * A specialized version of `reduce` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ //为数组类型数据提供的reduce方法 function arrayReduce(array, iteratee, accumulator, initAccum) { let index = -1//循环索引 const length = array == null ? 0 : array.length//数组长度 if (initAccum && length) {//如果没有提供累加器初始值,且数组至少有一个元素,累加器初始值就是数组第一个元素 accumulator = array[++index] } while (++index < length) {//循环累加 accumulator = iteratee(accumulator, array[index], index, array) } return accumulator } export default arrayReduce
baseReduce
/** * The base implementation of `reduce` and `reduceRight` which iterates * over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ //reduce基础实现,使用eachFunc方法执行累加的方法 function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, (value, index, collection) => { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection) //如果没有提供累加初始值,就用第一个元素作为初始值 }) return accumulator } export default baseReduce
baseEach
import baseForOwn from './baseForOwn.js' import isArrayLike from '../isArrayLike.js' /** * The base implementation of `forEach`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ //forEach的基础实现 //collection被迭代遍历的对象,iteratee遍历器 function baseEach(collection, iteratee) { if (collection == null) {//如果collection为空,直接返回原对象 return collection } if (!isArrayLike(collection)) {//如果collection不是array-like对象,就调用baseForOwn处理 return baseForOwn(collection, iteratee) } const length = collection.length//对象长度 const iterable = Object(collection) let index = -1//循环索引 while (++index < length) {//循环调用iteratee方法,如果iteratee返回值是false,提前跳出循环结束 if (iteratee(iterable[index], index, iterable) === false) { break } } return collection } export default baseEach
baseForOwn
import baseFor from './baseFor.js' import keys from '../keys.js' /** * The base implementation of `forOwn`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ //forOwn方法的基础实现 function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys)//如果object不为空,调用baseFor处理 } export default baseForOwn
baseFor
/** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ //baseForOwn的基础实现,通过keysFunc遍历对象每一个属性,用iteratee处理每个属性值 //iteratee可以返回false跳出循环 function baseFor(object, iteratee, keysFunc) { const iterable = Object(object) const props = keysFunc(object)//key组成的数组 let { length } = props//key数组长度 let index = -1//循环索引 while (length--) {//遍历key数组 const key = props[++index]//当前key if (iteratee(iterable[key], key, iterable) === false) {//调用iteratee break } } return object } export default baseFor
keys
import arrayLikeKeys from './.internal/arrayLikeKeys.js' import isArrayLike from './isArrayLike.js' /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @since 0.1.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @see values, valuesIn * @example * * function Foo() { * this.a = 1 * this.b = 2 * } * * Foo.prototype.c = 3 * * keys(new Foo) * // => ['a', 'b'] (iteration order is not guaranteed) * * keys('hi') * // => ['0', '1'] */ //创建一个给定对象的自身可枚举属性组成的数组 function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : Object.keys(Object(object)) //如果object是array-like对象,就调用arrayLikeKeys,否则使用原生的Object.keys方法 } export default keys
arrayLikeKeys
import isArguments from '../isArguments.js' import isBuffer from '../isBuffer.js' import isIndex from './isIndex.js' import isTypedArray from '../isTypedArray.js' /** Used to check objects for own properties. */ const hasOwnProperty = Object.prototype.hasOwnProperty /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ //创建一个给定array-like对象的自身可枚举属性组成的数组 function arrayLikeKeys(value, inherited) { const isArr = Array.isArray(value)//是否是数组 const isArg = !isArr && isArguments(value)//是否是arguments对象 const isBuff = !isArr && !isArg && isBuffer(value)//是否是buffer对象 const isType = !isArr && !isArg && !isBuff && isTypedArray(value)//是否是typedArray const skipIndexes = isArr || isArg || isBuff || isType//这四种类型需要跳过数字索引 const length = value.length//value的长度 const result = new Array(skipIndexes ? length : 0)//结果数组 let index = skipIndexes ? -1 : length//循环索引 while (++index < length) { result[index] = `${index}` } for (const key in value) {//循环属性,将非index属性和非特殊属性push进结果数组 if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. (key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length)) ))) { result.push(key) } } return result } export default arrayLikeKeys

浙公网安备 33010602011771号