3

Recently i have been asked to write a javascript function (it was a coding test) where they wanted me to implement a function which will add and return the values.

add(3,2);//should return 5
add(3)(2); //should return 5

I am not sure whether this is possible at all. I am not an expert in javascript so could get any clue from google search.

Tamil
  • 1,173
  • 1
  • 13
  • 35
  • 1
    The mechanism you need is called `currying`. See more [here](http://stackoverflow.com/questions/18431457/how-curry-function-should-really-work) and [here](http://ejohn.org/blog/partial-functions-in-javascript/). IMHO, the best example among JS frameworks - [this](http://lodash.com/docs#curry) (just to get know). – Kiril Aug 22 '14 at 06:59

2 Answers2

5

You would have to check whether the second argument was given first; if so, return the result immediately; otherwise, return a function that will complete the addition:

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

Alternatively, if you don't like the duplicate logic:

function add(a, b)
{
    var f = function(b) {
        return a + b;
    };

    return typeof b == 'undefined' ? f : f(b);
}

This is also referred to as partial function application or currying.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 1
    Nice. This is an example of currying in functional programming. You can find a generic form and read more about it here: http://tech.pro/tutorial/2011/functional-javascript-part-4-function-currying – sahbeewah Aug 22 '14 at 06:59
  • 1
    Thanks jack and everyone else. I was not aware of the word currying. Now i'll explore more on currying :) – Tamil Aug 22 '14 at 07:08
  • @sahbeewah Yeah, or partial function application :) – Ja͢ck Aug 22 '14 at 07:13
0

Solution For add(x,y):

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

Solution For add(x)(y):

function add(x) {
  return function(y){
    return x+y;
  }
}
ADev
  • 1
  • 1