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

后端 未结 28 2415
长发绾君心
长发绾君心 2020-11-27 14:11

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\

28条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 14:46

    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))
    

提交回复
热议问题