I need to make the following(below) function call to give the same result in both situations:
sum(5,4); // 9
sum(5)(4); // this should also print 9
I tried the following but it's not working:
function sum(x,y){
var a = x;
var b = y;
if (y == undefined && y == ''){
return function (a,b){
return a +b;
}
}
else {
return a +b;
}
}
Any suggestions?
Try to curry
your function for your requirement,
function sum(x,y){
if(y === undefined){
return function(y){ return x+y; }
} else {
return x + y;
}
}
sum(5,4); // 9
sum(5)(4); // 9
The "cool" one line answer:
function sum(x, y){
return y != undefined? x+y : function(a){return x + a};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With