I have been struggling to understand how to solve a problem below. I understand that it involves currying and I was able to come up with the answer if argument in sum()
is included. However, I can't figure out how to solve it with sum()
being empty.
I was able to come up with a solution for having a function invocation at the end s(1)()
, but not for s(1)
.
var sum = function() { /* put your code here */};
var s = sum();
alert(s); // 0
alert(s(1)); // 1
alert(s(1)(2)); // 3
alert(s(3)(4)(5)); // 12
This is solution that works with all parameters being included and ()
at the end.
var sum = function(a){
return function(b){
if(b !== undefined){
return sum(a+b);
}
return a;
}
};
For the first s
call console.log(s)
, I was only able to come up with simple solution below, to be able to return 0. It seems to be impossible to return 0 and then return a function such as s(1)
.
var sum = function(a){
if(!arguments.length) return 0;
};
var s = sum();
console.log(s);