JavaScript curry

前端 未结 5 769
我在风中等你
我在风中等你 2020-12-14 11:32

I`m a newbie at JavaScript trying to understand this tutorial about currying from Oreilly JavaScript Cookbook.

Could someone be kind enough to explain this program i

5条回答
  •  时光取名叫无心
    2020-12-14 11:51

    Squeegy posted a good breakdown, but I figured I'd add mine too.

    //Things to note, 'arguments' is a special variable in javascript that holds 
    //an array like object full of all the things passed into a function.
    //You can test this out with a function like this:
    //var alertArgs = function(){alert(arguments);};
    
    function curry(fn, scope) {
        //Either use the passed in 'scope' object, or the window object as your scope
        scope = scope || window;
        //Create a new array for storing the arguments passed into this function
        var args = [];
        //Loop through the extra arguments (we start at '2' because the first two
        //arguments were stored in `fn` and `scope` respectively.
        //We store these in the temporary 'args' array.
        //(in the example, args will end up looking like: [3.0, 4.0])
        for (var i = 2, len = arguments.length; i < len; ++i) {
            args.push(arguments[i]);
        }
        //We return the 'curried' function
        return function() {
            //This array is not used. I assume it is an error.
            var args2 = [];
            //We now have a new set of arguments, passed in to the curried function
            //We loop through these new arguments, (in the example, 6.42 and 8.0)
            //and add them to the arguments we have already saved. In the end, we have
            //the args array looking like: [3.0, 4.0, 6.42, 8.0]
            for (var i = 0; i < arguments.length; i++) {
                args.push(arguments[i]);
            }
            //This line isn't needed, because args2 is always blank.
            var argstotal = args.concat(args2);
    
            //Finally we call the function, passing in the full array of arguments
            return fn.apply(scope, argstotal);
        };
    }
    
    //This function takes 4 arguments
    function diffPoint(x1, y1, x2, y2) {
        return [Math.abs(x2 - x1), Math.abs(y2 - y1)];
    }
    
    //We partially apply the first 2 arguments, so x1 is always 3.0, 
    //and y1 is always 4.0
    var diffOrigin = curry(diffPoint, null, 3.0, 4.0);
    
    //We can now call 'diffPoint' indirectly, without having to specify 
    //3.0, 4.0 as the first 2 arguments.
    var newPt = diffOrigin(6.42, 8.0); //produces array with 3
    

提交回复
热议问题