How can I make var a = add(2)(3); //5 work?

I want to make this syntax possible:

var a = add(2)(3); //5

based on what I read at http://dmitry.baranovskiy.com/post/31797647

I've got no clue how to make it possible.


Solution 1:

You need add to be a function that takes an argument and returns a function that takes an argument that adds the argument to add and itself.

var add = function(x) {
    return function(y) { return x + y; };
}

Solution 2:

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

Ah, the beauty of JavaScript

This syntax is pretty neat as well

function add(x) {
    return function(y) {
        if (typeof y !== 'undefined') {
            x = x + y;
            return arguments.callee;
        } else {
            return x;
        }
    };
}
add(1)(2)(3)(); //6
add(1)(1)(1)(1)(1)(1)(); //6

Solution 3:

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

First-class functions and closures do the job.

Solution 4:

It's about JS curring and a little strict with valueOf:

function add(n){
  var addNext = function(x) {
    return add(n + x);
  };

  addNext.valueOf = function() {
    return n;
  };

  return addNext;
}

console.log(add(1)(2)(3)==6);//true
console.log(add(1)(2)(3)(4)==10);//true

It works like a charm with an unlimited adding chain!!