zoukankan      html  css  js  c++  java
  • JavaScript-Curry

    Currying allows you to easily create custom functions by partially invoking an existing function. Here’s a simple example:

    var add = function(a,b) {
        return a + b;
    }
    
    var addTen = add.curry(10); //create function that returns 10 + argument
    addTen(20); //30

    Generally, curry returns a copy of the invoking function, with its first n arguments pre-assigned with the arguments passed by the curry invocation.

    The curry function does not exist in native JavaScript, but it’s easy to write your own. Here I’m augmenting function’s prototype with an implementation based on the Prototype framework. (Notice I’m also throwing in a toArray function for convenience. This is because function’s arguments property is not a true array, and we need it to work with array’s concat function)

    function toArray(enum) {
        return Array.prototype.slice.call(enum);
    }
    
    Function.prototype.curry = function() {
        if (arguments.length<1) {
            return this; //nothing to curry with - return function
        }
        var __method = this;
        var args = toArray(arguments);
        return function() {
            return __method.apply(this, args.concat(toArray(arguments)));
        }
    }

    The returned function expects to be invoked with additional argument(s) which it will concatenate with the argument(s) it got from the curry function.

    A CURRY FUNCTION IN JAVASCRIPT

    function curry (fn, scope) {
    
        var scope = scope || window;
    
        var args = [];
    
        for (var i=2, len = arguments.length; i < len; ++i) {
    
            args.push(arguments[i]);
    
        };
    
        return function() {
    
            fn.apply(scope, args);
    
        };
    
    }

    Quote From:

    Curry: cooking up tastier functions

    JavaScript currying

  • 相关阅读:
    poj 1753 Flip Game
    SDIBT 2345 (3.2.1 Factorials 阶乘)
    HDU 1176 免费馅饼
    HDU 1058 Humble Numbers
    HDU 1003 MAXSUM(最大子序列和)
    HDU1864 最大报销额
    HDU 1114 Piggy-Bank(完全背包)
    POJ 3624 Charm Bracelet
    处理textarea里Enter(回车换行符)
    uniApp打卡日历
  • 原文地址:https://www.cnblogs.com/liao-hua/p/4753652.html
Copyright © 2011-2022 走看看