lodash源码之add

1、使用场景 add方法用于计算两个数的和 _.add(6, 4); // => 10 2、源码分析 add.js import createMathOperation from './.internal/createMathOperation.js' const add = createMathOperation((augend, addend) => augend + addend, 0) export default add 可以看到,add方法的源码很短。首先引入一个createMathOperation方法,执行该方法并赋值给add。 createMathOperation是一个高阶函数,高阶函数就是一个函数可以接收另一个函数作为参数,可以看到它接收了一个箭头函数作为参数。实际上add方法的核心内容就在createMathOperation这个方法里。 createMathOperation.js import baseToNumber from './baseToNumber.js' import baseToString from './baseToString.js' function createMathOperation(operator, defaultValue) { return (value, other) => { // 如果执行add函数时不传参。add() => 0 if (value === undefined && other === undefined) { return defaultValue } // 如果执行add函数时只传一个参数,返回该参数。add(1) => 1 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 这个函数返回了一个箭头函数,因为前面add.js里面执行createMathOperation这个方法后赋值给add这个变量,所以这个箭头函数被赋值给了add这个变量,箭头函数里面的两个参数value和other便是add方法执行时传入的那两个参数。 继续往下看,这个箭头函数里面首先做了很多判断,对add()方法传入的不同参数类型做了一些处理: 1. 执行add函数的时候不传参,add() => 0 if (value === undefined && other === undefined) { // defaultValue是add.js中createMathOperation方法的第二个参数,为0 return defaultValue } 2. 执行add函数时只传一个参数,返回该参数 if (value !== undefined && other === undefined) { return value } if (other !== undefined && value === undefined) { return other } 3. add方法传入的参数含有字符串,就把两个参数都转换成string类型 if (typeof value === 'string' || typeof other === 'string') { value = baseToString(value) other = baseToString(other) } 4. 别的情况都转换成number类型 else { value = baseToNumber(value) other = baseToNumber(other) } 最后把转换好的参数传入operator()这个函数里,该函数就是add.js里调用createMathOperation这个高阶函数传入的第一个参数:(augend, addend) => augend + addend

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):