每日lodash源码阅读(一)——createMathOperation
一、写在前面
createMathOperation
是lodash的数学操作内置函数,add、divide等方法均是通过createMathOperation
创建出来的,阅读createMathOperation
可以掌握lodash的add
、divide
等方法。
二、使用举例
_.add(6, 4)
三、源码分析
add.js
import createMathOperation from './.internal/createMathOperation.js'
const add = createMathOperation((augend, addend) => augend + addend, 0)
export default add
可以看到,add方法很简单,就是调用createMathOperation方法,把结果赋值给add。
实际上,createMathOperation是一个高阶函数,接受一个函数作为参数,返回另一个函数。
createMathOperation.js
import baseToNumber from './baseToNumber.js'
import baseToString from './baseToString.js'
function createMathOperation(operator, defaultValue) {
return (value, other) => {
// 调用add等函数,不传参,返回defaultValue(add等函数固定传入的defaultValue,比如上文中add传入的defaultValue是0)
if (value === undefined && other === undefined) {
return defaultValue
}
// 调用add等函数,只传一个合法参数,则把这个合法参数返回
if (value !== undefined && other === undefined) {
return value
}
if (other !== undefined && value === undefined) {
return other
}
// 如果传入的参数含有字符串,则把两个参数都转换成string类型,add(1, '1') => '11'
if (typeof value === 'string' || typeof other === 'string') {
value = baseToString(value)
other = baseToString(other)
}
else {// 否则都转换成number类型
value = baseToNumber(value)
other = baseToNumber(other)
}
// 将转换好的参数传入调用createMathOperation函数时传入的operator函数
return operator(value, other)
}
}
export default createMathOperation
createMathOperation返回了一个箭头函数,做了很多类型判断,最终执行add等方法传入的operator函数。
createMathOperation作为一个高阶函数,主要作用就是增加了参数校验功能