Skip to content
Advertisement

Javascript function challenge add(1,2) and add(1)(2) both should return 3

A friend of mine challenged me to write a function that works with both of these scenarios

add(2,4)  // 6
add(2)(4) // 6

My instinct was the write an add() function that returns itself but I’m not sure I’m heading in the right direction. This failed.

function add(num1, num2){
    if (num1 && num2){
        return num1 + num2;
    } else {
        return this;
    }
}

alert(add(1)(2));

So I started reading up on functions that return other functions or return themselves.

I am going to keep trying, but if someone out there has a slick solution, I’d love to see it!

Advertisement

Answer

There is an article on Dr.Dobs Journal about “Currying and Partial Functions in JavaScript” which describes exactly this problem.

One solution found in this article is:

// a curried add
// accepts partial list of arguments
function add(x, y) {
     if (typeof y === "undefined") { // partial
        return function (y) {
              return x + y;
        };
     }
   // full application
   return x + y;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement