I need a js sum function to work like this:
sum(1)(2) = 3
sum(1)(2)(3) = 6
sum(1)(2)(3)(4) = 10
etc.
I heard it can\'t be done. But heard
Here's a more generic solution that would work for non-unary params as well:
const sum = function (...args) {
let total = args.reduce((acc, arg) => acc+arg, 0)
function add (...args2) {
if (args2.length) {
total = args2.reduce((acc, arg) => acc+arg, total)
return add
}
return total
}
return add
}
document.write( sum(1)(2)() , '
') // with unary params
document.write( sum(1,2)() , '
') // with binary params
document.write( sum(1)(2)(3)() , '
') // with unary params
document.write( sum(1)(2,3)() , '
') // with binary params
document.write( sum(1)(2)(3)(4)() , '
') // with unary params
document.write( sum(1)(2,3,4)() , '
') // with ternary params