Search code examples
javascriptchaining

How to achieve arbitrary chain on function call in javascript?


I have written code to achieve

sum(1)(2) //3

the code looks like:

function sum(a) {

  return function(b) { 
    return a+b
 }

}

But I didn't work out the second question, which is how to achieve any arbitrary number of chain function call like:

sum(1)(2) == 3
sum(5)(-1)(2) == 6
sum(6)(-1)(-2)(-3) == 0
sum(0)(1)(2)(3)(4)(5) == 15

Solution

  • Normally you'd do something like this:

    var add = function(a,b){
        return a+b;
    };
    
    var sum = function(){
        return [].reduce.call(arguments, add);
    }
    

    And then you can write:

    sum(1,2,3,4); // 10
    

    But it is possible to hack the functionality you're after:

    var sum = function(x){
        var f = function(y){
            return sum(x+y);
        };
        f.valueOf = function(){
            return x;
        };
        return f;
    };
    
    sum(1)(2)(3)(4); // 10
    

    Just don't do it in production code please!