• 柯里化学习


    把函数变为接收一个参数,返回一个值得固定形式.

    f(x,y,z) -> f(x)(y)(z)

    特性

    1 匿名函数
    2 每个函数只有一个输入参数

    function currying(fn) {
       var args = [].slice.call(arguments, 1);
       return function() {
            var newArgs = args.concat([].slice.call(arguments));
            return fn.apply(null, newArgs);
       }
    }
    
    var add = function(x,y) {
      return x + y;
    }
    
    var result = curry(add, 5);
    
    console.log(result(10));
    
    function curryRight(fn) {
        var args = [].slice.call(arguments, arguments.length -1 );
        return function() {
            var newArgs = [].concat([].slice.call(arguments), args);
            return fn.apply(null, newArgs);
        }
    }
    
    function curry(fn, length) {
        // capture fn's # of parameters
        length = length || fn.length;
        return function () {
            if (arguments.length < length) {
                // not all arguments have been specified. Curry once more.
                var combined = [fn].concat(toArray(arguments));
                return length - arguments.length > 0
                    ? curry(sub_curry.apply(this, combined), length - arguments.length)
                    : sub_curry.call(this, combined );
            } else {
                // all arguments have been specified, actually call function
                return fn.apply(this, arguments);
            }
        };
    }
    
    var fn = curry(function(a, b, c) { return [a, b, c]; });
    
    // these are all equivalent
    fn("a", "b", "c");
    fn("a", "b", "c");
    fn("a", "b")("c");
    fn("a")("b", "c");
    fn("a")("b")("c");
    //=> ["a", "b", "c"]
    
  • 相关阅读:
    Flink
    数据工程师
    数据库中间件
    数据仓库
    数据库
    设计模式
    机器学习
    Collections
    Concurrency
    Java
  • 原文地址:https://www.cnblogs.com/mayufo/p/5850560.html
Copyright © 2020-2023  润新知