The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that?
function add () {
}
add(1)(2)(3)(); //6
add(5)(6)(7)(8)(9)() //35
The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that?
function add () {
}
add(1)(2)(3)(); //6
add(5)(6)(7)(8)(9)() //35
I think this is exactly what you need:
function add(value) {
return (val) => val !== undefined ? add(value + val) : value;
}
console.log(add(2)(2)()); //4
console.log(add(2)(2)(5)(5)()); //14
console.log(add(1)(1)(1)(1)(1)()); //5
console.log(add(1)(1)(0)(1)(1)()); //4
How it works
For every call it declares a function inside, in result it creates a closure(persistent scope) in every call. Function created in that way has access to its parameter + previous call parameter due to existing closure.
So if I call add(2)(3)():
To finish the computation pipe the last call needs to be without a value.
The basic idea is to create a closure with a variable sum
that we can update, and return the sum
if the value is undefined, or the the inner function:
const add = (n) => {
let sum;
const inner = (n) => n === undefined ? sum : (sum = (sum || 0) + n, inner);
return inner(n);
};
console.log(add(1)(2)(3)()); //6
console.log(add(5)(6)(7)(8)(9)()); //35
I would just use a Spread syntax like this:
function add(...values) {
return values.reduce((sum, value) => sum + value, 0)
}
console.log(add(1, 4, 34, 45, 3, 4, 5))