Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the same result by using function and closure together in javascript

Tags:

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 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?

like image 299
User123 Avatar asked Feb 23 '16 12:02

User123


2 Answers

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
like image 62
Rajaprabhu Aravindasamy Avatar answered Nov 14 '22 22:11

Rajaprabhu Aravindasamy


The "cool" one line answer:

function sum(x, y){ 
   return y != undefined? x+y : function(a){return x + a}; 
}
like image 43
Julien Leray Avatar answered Nov 14 '22 23:11

Julien Leray