柯里化

若如初见. 提交于 2020-02-08 21:33:08
// 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())

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!