本文为lodash源码分析的第12篇,后续会持续更新这个专题,欢迎指正。
依赖
import baseToNumber from './baseToNumber.js'
import baseToString from './baseToString.js'
源码分析
createMathOperation函数的主要作用是返回一个函数,可以对两个值进行数学运算。具体的运算逻辑由operator函数提供。
function createMathOperation(operator, defaultValue) {
return (value, other) => {
if (value === undefined && other === undefined) {
return defaultValue
}
if(value === undefined || other === undefined) {
return value || 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)
}
}
该函数返回一个箭头函数,该箭头函数接受两个参数value和other,返回一个具体的值。具体的逻辑如下:
- 如果两个参数都是
undefined,返回默认值defaultValue; - 如果其中一个为
undefined, 返回另一个不为undefined的值; - 如果其中任一个参数为
string类型,调用baseToString函数转为string类型; - 否则,调用
baseToNumber函数把两者转为number类型; - 最后,对两个参数调用
operator函数,并将计算结果返回。