zoukankan      html  css  js  c++  java
  • JavaScript Curry

     感觉就是C++中的 functor+bind.

    http://stackoverflow.com/questions/5176313/javascript-curry

    // define the curry() function
    
    function curry(fn, scope) {
    
        // set the scope to window (the default global object) if no scope was passed in.
        scope = scope || window;
    
        // Convert arguments into a plain array, because it is sadly not one.
        // args will have all extra arguments in it, not including the first 2 (fn, scope)
        // The loop skips fn and scope by starting at the index 2 with i = 2
        var args = [];
        for (var i = 2, len = arguments.length; i < len; ++i) {
            args.push(arguments[i]);
        }
    
        // Create the new function to return
        return function() {
    
            // Convert any arguments passed to the this function into an array.
            // This time we want them all
            var args2 = [];
            for (var i = 0; i < arguments.length; i++) {
                args.push(arguments[i]);
            }
    
            // Here we combine any args originally passed to curry, with the args
            // passed directly to this function.
            //   curry(fn, scope, a, b)(c, d)
            // would set argstotal = [a, b, c, d]
            var argstotal = args.concat(args2);
    
            // execute the original function being curried in the context of "scope"
            // but with our combined array of arguments
            return fn.apply(scope, argstotal);
        };
    }
    
    // Create a function to be curried
    
    function diffPoint(x1, y1, x2, y2) {
        return [Math.abs(x2 - x1), Math.abs(y2 - y1)];
    }
    
    // Create a curried version of the diffPoint() function
    //   arg1: the function to curry
    //   arg2: the scope (passing a falsy value causes the curry function to use window instead)
    //   arg3: first argument of diffPoint() to bake in (x1)
    //   arg4: second argument of diffPoint() to bake in (y1)
    var diffOrigin = curry(diffPoint, null, 3.0, 4.0);
    
    // Call the curried function
    // Since the first 2 args where already filled in with the curry, we supply x2 and y2 only
    var newPt = diffOrigin(6.42, 8.0);
  • 相关阅读:
    You don't have permission to access / on this server.
    WampServer修改端口及菜单Localhost
    如何手机访问电脑服务器上的网页?
    Zed Shaw:程序员的常见健康问题
    js中匿名函数的N种写法
    HDU 1561 树形DP背包问题
    COJ 1156 Switching bulbs
    POJ 2891 Strange Way to Express Integers
    FZU 1402 猪的安家 中国剩余定理
    HDU 1573 解同余模线性方程组
  • 原文地址:https://www.cnblogs.com/lambdatea/p/3388294.html
Copyright © 2011-2022 走看看