0

I'm trying to make a function work with this two calls:

func(1)(2); // 3
func(1, 2); // 3;

What i'm trying to do:

function func(x, y) {
  return (function(y) {
    return x + y;
  }(y));
}

But this won't work at all when i try to call in sequence. Is there other way to achieve that?

function add(x, y) {
  if (y) return x + y;
  return function(y) {
    return x + y;
  };
}

This would work, but i think it could be a better solution.

Thanks.

  • 1
    Possible duplicate of [How to Write a function where the output for both “sum(2,3)” and “sum(2)(3)” will be 5](http://stackoverflow.com/questions/42952425/how-to-write-a-function-where-the-output-for-both-sum2-3-and-sum23-wil) – Meirion Hughes Apr 11 '17 at 20:06

2 Answers2

0

What you are looking for is called currying, here is how you could do it.

function add(a, b){
 if(typeof b !== 'undefined'){
  return a + b;  
 }else{
  return function(c){
   return a + c;
  }
 }
 
 
}


console.log(add(2, 3));

console.log(add(2)(3));

Also check this answer How to Write a function where the output for both “sum(2,3)” and “sum(2)(3)” will be 5

Community
  • 1
  • 1
azs06
  • 3,467
  • 2
  • 21
  • 26
0

this is no good reason to do that, IMO, you have a function func(1, 2), if you want to currify that, just wrapper it with curry, if you use lodash, you can curry a function with var curried = _.curry(function), that makes your function clean

Sean
  • 2,990
  • 1
  • 21
  • 31