How to get the same result using function and closure in javascript

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 did not work:

 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?

+6
source share
4 answers

Try 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 
+4
source

You should use a logical OR (||), not AND (& &)

 function sum(x,y){ if (y == undefined || y == ''){ return function (y){ return x + y; } } else { return x + y; } } 
+3
source

"Cool" answer on one line:

 function sum(x, y){ return y != undefined? x+y : function(a){return x + a}; } 
+3
source

Caution: you probably do not need this functionality, it is simply redundant.

You can use the air conditioner as follows:

 function sum( x , y ){ if(y == undefined){ return function( y ){ return x + y; }; } else{ return x + y; } } 
+2
source

All Articles