每日lodash源码阅读(一)——createMathOperation
- 一、写在前面
- 二、使用举例
- 三、源码分析
- add.js
- createMathOperation.js
一、写在前面
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) => {
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)
}
}
export default createMathOperation
createMathOperation返回了一个箭头函数,做了很多类型判断,最终执行add等方法传入的operator函数。
createMathOperation作为一个高阶函数,主要作用就是增加了参数校验功能
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)