动态currying,以及如何在JavaScript变量中保存函数和值

Bra*_*rad 6 javascript currying

我正在学习JavaScript,最近我遇到了一个练习题,要求我构建一个可以创建输出的函数,如下所示:

var threeSum= sum(3);
threeSum //3
threeSum(4) //7
threeSum(4)(3) //10
threeSum(4)(3)(7) //17
threeSum(4)(3)(7)()(2) //19
threeSum - 2 //1
threeSum + 2 //5
Run Code Online (Sandbox Code Playgroud)

我认为涉及到currying,我认为我已经基本掌握了curry如何以简单的形式工作

a=>b=>c=> a+b+c
Run Code Online (Sandbox Code Playgroud)

但我不知道如何创建一个能够处理不确定数量的输入的curried函数,也不知道如何使它成为一个可以作为值和函数的变量.

任何见解都表示赞赏!我只需要朝着正确的方向努力 - 此时我甚至不知道我在寻找什么.

Eri*_*ric 5

这里的窍门是您需要定义valueOf,它允许javascript将一个对象(如函数)解释为一个值:

var valueAndCallable = function(x) {
    var res = function(a) { return a + x };
    res.valueOf = function() { return x; };
    return res;
};

var v = valueAndCallable(1)
console.log(v);      // function ... -
console.log(+v);     // 1 - calls .valueOf()
console.log(1 + v);  // 2 - calls .valueOf()
console.log(v(3));   // 4
Run Code Online (Sandbox Code Playgroud)

对于currying,您只想res()同时返回valueAndCallable。