jiaochunxiao / fe-blog

好好学习,天天向上
1 stars 1 forks source link

sum(1)(2)(3) == sum(1,2,3) #1

Open jiaochunxiao opened 4 years ago

jiaochunxiao commented 4 years ago
function sum(..._args) {
    const _adder = function (...rest) {
        _args.push(...rest);
        return _adder;
    }
    _adder.toString = function () {
        return _args.reduce(function (a, b) {
            return a + b;
        });
    };
    return _adder;
}
jiangzhenxiang commented 4 years ago

柯理化


function curry(func) {
    // func 是要转换的函数
    return function curried(...args) {
        // func.length指函数的形参个数
        if (args.length >= func.length) {
            //  如果传入的 args 长度与原始函数所定义的(func.length)相同或者更长,那么只需要将调用传递给它即可
            return func.apply(this, args);
        } else {
            return function (...args2) {
                return curried.apply(this, args.concat(args2));
            };
        }
    };
}
function sum(a, b, c) {
    return a + b + c;
}

let curriedSum = curry(sum);

console.log(curriedSum(1, 2, 3)); // 6,仍然可以被正常调用
console.log(curriedSum(1)(2, 3)); // 6,对第一个参数的柯里化
console.log(curriedSum(1)(2)(3)); // 6,全柯里化