Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve arbitrary chain on function call in javascript? [duplicate]

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
like image 883
Huibin Zhang Avatar asked Oct 30 '14 15:10

Huibin Zhang


2 Answers

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!

like image 130
1983 Avatar answered Sep 27 '22 21:09

1983


You can't do this - how does the sum function know whether you want it to return the answer or another function?

You could do something along these lines though:

sum(0)(1)(2)(3).result()

Implemented like this:

var sum = (function(){
    var total = 0;
    var f = function(n){
        total += n;
        return f;
    };
    f.result = function(){
        return total;
    };
    return f;
}());
like image 38
codebox Avatar answered Sep 27 '22 22:09

codebox