一、lodash版本:4.17.5
二、函数:
1、add
1)含义:两个月相加
2) 例子。
const _ = require('lodash’);
console.log(_.add(10, 20));// 输出:30
3) 源码解读。
源码:
const INFINITY = 1 / 0
const symbolProto = Symbol ? Symbol.prototype : undefined
const symbolToString = symbolProto ? symbolProto.toString : undefined
const add = createMathOperation((augend, addend) => augend + addend, 0)
function baseToNumber(value) {
if (typeof value == 'number') {
return value
}
if (isSymbol(value)) {
return NAN
}
return +value
}
function isSymbol(value) {
const type = typeof value
return type == 'symbol' || (type == 'object' && value != null && getTag(value) == '[object Symbol]')
}
解读:
(1)在createMathOperation函数中,前三个if判断value和other是否为空,如果都为空就返回defaultValue(也就是0)。如果有一个为空,就返回另外一个不为空的值。接着判断value和other是否字符型,如果是,则调用baseToNumber。核心源代码,如下所示:
function createMathOperation(operator, defaultValue) {
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)
}
}
实例如下:
const _ = require('lodash');
console.log(_.add(undefined, undefined)) // 输出:0
console.log(_.add(1, '')); // 输出:1
(2)在baseToString中,如果传入的参数是字符串,那么直接返回该字符串进行计算。核心代码,如下所示:
if (ty