import createMathOperation from './.internal/createMathOperation.js'
/**
* Adds two numbers.
*
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* add(6, 4)
* // => 10
*/
const add = createMathOperation((augend, addend) => augend + addend, 0)
export default add
import baseToNumber from './baseToNumber.js'
import baseToString from './baseToString.js'
/**
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
*/
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
1.createMathOperation,做校验和转化用
2.operator:add的参数,函数作为参数
3.add实际上就是operator
使用场景:
add自然变成用在相加
operator这种方式,在闭包中用的比较多,或者回调,比如setTimeout,callback,promise等等;
createMathOperation,去对参数做处理.
而返回一个函数的做法,在我现阶段而言,值得我去学习,这里虽然是一个简单的函数的校验,但是可以用在诸多地方,去实现生成一个函数,去处理对象,事件和方法.