views:

179

answers:

4

Make this syntax possible:

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

I got this question at http://dmitry.baranovskiy.com/post/31797647

Got no clue. Confused.... Know the answer...

+11  A: 

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; };
}
tvanfosson
26 secs faster. You win.
NV
+8  A: 
function add(x){
  return function(y){
    return x+y
  }
}

First-class functions and closures do the job.

NV
+6  A: 
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
Oscar Kilhed
`if (y)` should be `if (typeof y === "undefined")`, since zero is a valid argument.
Matthew Crumley
and x + 0 is x again, so it is actually correct =)
dionadar
@dionadar well, not exactly (0) will return the value of x wich is not a function so you can't add anything else after you've used (0).
Oscar Kilhed
+2  A: 

in addition to what's already said, here's a solution with generic currying (based on http://github.com/sstephenson/prototype/blob/master/src/lang/function.js#L180)

Function.prototype.curry = function() {
    if (!arguments.length) return this;
    var __method = this, args = [].slice.call(arguments, 0);
    return function() {
      return __method.apply(this, [].concat(
        [].slice.call(args, 0),
        [].slice.call(arguments, 0)));
   }
}


add = function(x) {
    return (function (x, y) { return x + y }).curry(x)
}

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