I was presented with question and I had no idea how to do it
add() - > returns 0
add(1)() -> returns 1
add(1)(2)() -> returns 3
add(1)(2)(3)(4)() -> 10
Basically it can go on
I was presented with question and I had no idea how to do it
add() - > returns 0
add(1)() -> returns 1
add(1)(2)() -> returns 3
add(1)(2)(3)(4)() -> 10
Basically it can go on
Here is my one line solution if you love aesthetics
const add = (val) => (val ? (arg) => (arg ? add(val + arg) : val) : 0);
console.log(add(1)(2)(3)())
For Readability:
const add = (val) => {
if (val) {
return (arg) => {
if (arg) {
return add(val + arg);
} else {
return val;
}
};
}
return 0;
};
console.log(add(1)(2)(3)())
Edit : Explaination
I'll try to explain it in a simple way
lets break it down with a example add(1)(2)(3)()
So it happens like this
add(1) is evaluated first
add(1) -> returns a function (say _add())
_add() is a closure so it has access to the val variable (with value 1) and has its own parameter args with value 2
_add(2) -> calls add() again with the result of the addition (val + args)
add(1)(2)(3)() becomes -> _add(2)(3)()
_add(2) checks if it has a parameter args and if it does then it computes val + args and returns add(val +args) else 0_add(2)(3)() becomes -> add(3)(3)()
add(3)(3)() becomes -> _add(6)()
add(6)() -> returns _add()_add() this time no parameter so return the valueI hope I was able to explain, comment if you have any doubts, I'll try my best
You can access the arguments through the variable arguments. Read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I'm using a basic for loop, mostly for clarity, to show case it below.
function add() {
var sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
/* Alternative loop
for (let number of arguments) {
sum += number;
} */
return sum;
}
console.log( add(1) );
console.log( add(1, 2) ); // returns 3
console.log( add(1, 2, 3, 4) ); // returns 10
I think you are looking for this.
function add(a){
func = function(b){
func.result+=b;
return func;
}
func.result = a;
return func;
}
console.log(add(2)(2).result);
Each sequential call returns the same function again. You can do it infinitely and access result as property of the returned function.