• 柯里化


    // bind 方法原理模拟
    // bind 方法的模拟
    Function.prototype.bind = function (context) {
        var self = this;
        var args = [].slice.call(arguments, 1);
    
        return function () {
            return self.apply(context, args);
        }
    }

    Function.prototype.bind = function(context, ...args){
      return () => {
        return this.apply(context, args);
      }
    }

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

    console.log(add.bind(null, 2, 3)())
     
    const curry = (fn, ...arg) => {
        let all = arg || [],
            length = fn.length;
        return (...rest) => {
            let _args = all.slice(0);
            _args.push(...rest);
            if (_args.length < length) {
                return curry.call(this, fn, ..._args);
            } else {
                return fn.apply(this, _args);
            }
        }
    }
    const add = curry((a, b) => a + b);
    const add6 = add(6);
    console.log(add6(1)); //7
    console.log(add6(2)); //8

    var curry = function(func,args){
    var length = func.length;
    args = args||[];

    return function(){
    newArgs = args.concat([].slice.call(arguments));
    if(newArgs.length < length){
    return curry.call(this,func,newArgs);
    }else{
    return func.apply(this,newArgs);
    }
    }

    }

    function sum (a, b, c){
    return a + b + c;
    }

    var addCurry = curry(sum);
    addCurry(1,2) //3
    addCurry(1)(2) //3
     
    function add (x) {
      let sum = x;
      const temp = function (y) {
        sum += y;
        return temp;
      }
      temp.toString = function () {
        return sum;
      }
      return temp;
    }
    
    console.log(add(1)(2)(3).toString())
  • 相关阅读:
    什么时候是个头?
    生活就是这样
    差距究竟在哪里?
    认识到三个问题
    研究生三件事
    重写DNN6.2注册、登陆、修改等个人中心
    SQL游标的使用
    SQL UPDATE实现多表更新
    SQL 百万级两表数据间更新和添加
    DNN路径
  • 原文地址:https://www.cnblogs.com/shangyueyue/p/10609943.html
Copyright © 2020-2023  润新知