How do you curry any javascript function of arbitrary arity?

前端 未结 5 1937
天命终不由人
天命终不由人 2020-12-19 04:19

Let\'s say I have some function:

function g(a,b,c){ return a + b + c }

And I\'d like to turn it into its \"curried\" form (in quotations si

5条回答
  •  时光取名叫无心
    2020-12-19 04:49

    Here's my attempt:

    function curry(fn, len) {
        if (typeof len != "number")
            len = fn.length; // getting arity from function
        return function curried() {
            var rlen = len - arguments.length;
            if (rlen <= 0) // then execute now
                return fn.apply(this, arguments);
            // else create curried, partially bound function:
            var bargs = [this]; // arguments for `bind`
            bargs.push.apply(bargs, arguments);
            return curry(fn.bind.apply(fn, bargs), rlen);
        };
    }
    

    This does not partial application (which is easy in JS with the bind method), but true functional currying. It works with any functions of arbitrary, but fixed arity. For variadic functions you would need a different execution trigger, maybe when no arguments are passed any more or an exec method like in @plalx' answer.

提交回复
热议问题