lodash源码阅读-add.js

add.js

// add.js
const add = createMathOperation((augend, addend) => augend + addend, 0) // 返回一个add函数
export default add

// createMathOperation.js
function createMathOperation(operator, defaultValue) { // operator是传入的函数参数,即上面的箭头函数(augend, addend) => augend + addend
  return (value, other) => { // 返回值是一个函数,接收两个参数
    if (value === undefined && other === undefined) {
      return defaultValue
    }
    if (value !== undefined && other === undefined) {
      return value
    }
    if (other !== undefined && value === undefined) {
      return other
    }
    if (typeof value === 'string' || typeof other === 'string') { // 若是两个参数中有一个是字符串类型,则统一转成字符串类型,而后进行操做
      value = baseToString(value)
      other = baseToString(other)
    }
    else { // 不然,都转成数字类型
      value = baseToNumber(value)
      other = baseToNumber(other)
    }
    return operator(value, other) // 返回operator函数的结果
  }
}
复制代码
相关文章
相关标签/搜索