写一个函数,达到以下效果
sum(1,2,3,4,5).valueOf() // 15
sum(1,2,3,4)(5).valueOf() // 15
sum(1,2)(3)(4)(5).valueOf() // 15
sum(1,2)(3,4)(5).valueOf() // 15
实现
// 方法一
const add = (...args) => {
const ArgArr = [...args]
let result = 0
if (ArgArr.length === 1) {
result = ArgArr[0]
} else {
result = ArgArr.reduce((val, currentVal) => val + currentVal)
}
return result
}
const sum = (...args) => {
let sum = add(...args)
let tmp = (...args) => {
sum = sum + add(...args);
return tmp
};
tmp.valueOf = () => {
return sum
}
return tmp
}
// 方法二
const sum = (...a) => {
let helper = (...b)=> sum(...a,...b)
helper.valueOf=()=>a.reduce((acc,num)=>acc+num)
return helper
}