lodash analysis
  • Introduction
  • Tips
    • 高阶函数
    • 从 ECMAScript 中理解 Symbol 类型转换
  • Array
    • findLastIndex
    • map
  • Collection
    • countBy
    • findLast
    • flatMap
    • partition
    • reduce
  • Function
    • after
    • before
    • debounce
    • defer
    • delay
    • flip
    • memoize
    • negate
    • once
    • overArgs
    • throttle
  • Lang
    • isArguments
    • isArrayLike
    • isBuffer
    • isLength
    • isObject
    • isObjectLike
    • isSymbol
    • isTypedArray
    • isUndefined
    • toFinite
    • toNumber
  • Math
    • add
    • ceil
    • divide
    • floor
    • maxBy
    • mean
    • meanBy
    • minBy
    • multiply
    • round
    • subtract
    • sum
    • sumBy
  • Number
    • clamp
    • inRange
    • random
  • Object
    • keys
  • .internal
    • arrayLikeKeys
    • arrayReduce
    • baseAssignValue
    • baseEach
    • baseFindIndex
    • baseFlatten
    • baseFor
    • baseForOwn
    • baseInRange
    • baseReduce
    • baseSum
    • baseToNumber
    • baseToString
    • createMathOperation
    • createRound
    • getTag
    • isFlattenable
    • isIndex
    • nodeTypes
  • Date
    • now(已弃用)
Powered by GitBook
On this page
  1. Collection

reduce

PreviouspartitionNextafter

Last updated 6 years ago

Was this helpful?

CtrlK
  • 依赖
  • 源码
  • 相关链接

Was this helpful?

"I'm not in this world to live up to your expectations and you're not in this world to live up to mine." —Bruce Lee

本文为 《lodash 源码阅读》 系列文章,后续内容会在 github 中发布,欢迎 star,gitbook 同步更新。

依赖

import arrayReduce from './.internal/arrayReduce.js';
import baseEach from './.internal/baseEach.js';
import baseReduce from './.internal/baseReduce.js';
  • lodash 源码阅读 —— arrayReduce

  • lodash 源码阅读 —— baseEach

  • lodash 源码阅读 —— baseReduce

源码

/**
 * 压缩 collection(集合)为一个值,通过 iteratee(迭代函数)遍历 collection(集合)中的每个元素,每次返回的值会作为下一次迭代使用。
 * 如果没有提供 accumulator,则 collection(集合)中的第一个元素作为初始值。
 * iteratee 调用4个参数:(accumulator, value, index|key, collection).
 *
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object} collection 用来迭代的集合。
 * @param {Function} iteratee 每次迭代调用的函数。

相关链接

  • MDN - Arguments

  • lodash 源码阅读 —— arrayReduce

  • lodash 源码阅读 —— baseEach

  • lodash 源码阅读 —— baseReduce

* @param {*} [accumulator] 初始值。
* @returns {*} 返回累加后的值。
*/
function reduce(collection, iteratee, accumulator) {
const func = Array.isArray(collection) ? arrayReduce : baseReduce;
const initAccum = arguments.length < 3;
// 根据 collection 类型选择调用 arrayReduce 或 baseReduce
return func(collection, iteratee, accumulator, initAccum, baseEach);
}