JS Function With Two Parentheses and Two Params

后端 未结 4 1545
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 09:16

I\'m trying to understand how a function works that is run with two parentheses and two parameters. Like so:

add(10)(10); // returns 20

I k

4条回答
  •  借酒劲吻你
    2020-12-15 09:51

    To extend what both T. J. Crowder and Benjamin Gruenbaum said, libraries like Ramda (disclosure: I'm one of the authors) allow you to convert a simple function like this:

    function add(a, b) {
        return a + b;
    }
    

    into the style under discussion by wrapping it in a call to a curry function:

    var add = R.curry(function add(a, b) {
        return a + b;
    });
    
    add(3, 5); //=> 8
    add(3)(5); //=> 8
    var add3 = add(3);
    add3(5); //=> 8
    

    The best article I know on this subject is Hugh Jackson's Why Curry Helps. I wrote a more detailed one at Favoring Curry.


    Update

    Here is a version of curry somewhat simpler than the one in Ramda. It would do the above and quite a bit more, but doesn't do some of the things that Ramda does with placeholder values:

    // here is a function that takes a function and returns a curried version
    // of it, that is, a version that performs the sort of partial application
    // you describe.
    var curry = function(fn) {
        // first, we detect how many arguments the function has.
        var fnArity = fn.length; 
        var partialApply = function(args) { 
            // now, let's create a function that's curried
            return function () {
                // collect the previous args as the partial, and add the new 
                // ones you just received
                var newArgs = (args || []).concat([].slice.call(arguments, 0));
                // if we have "enough" arguments, we don't need any more partial
                // application and we can call the function.
                if (newArgs.length >= fnArity) {
                    return fn.apply(this, newArgs);
                } else { // else we return a partially applied version
                    return partialApply(newArgs);
                }
            };
        };
    
        return partialApply([]); // a function is itself partially applied with 0 args
    };
    

提交回复
热议问题