柯里化

36 阅读1分钟

柯里化

const curry = (fn) => {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn.apply(null, args);
        }
        return (...following) => {
            return curried.apply(null, args.concat(following));
        };
    }
};
const add = (x, y, z, m) => {
    return x + y + z + m;
}

const plus = curry(add);
console.log(plus(1, 2, 3, 4)); // 10
console.log(plus(1, 2, 3)(4)); // 10
console.log(plus(1, 2)(3)(4)); // 10
console.log(plus(1)(2)(3)(4)); // 10 

const name = (age, name, sex) => {
    return `name:${name} age:${age} sex:${sex}`;
}
const plustname = curry(name); 
console.log(plustname(125)("哈哈哈")("男"));// name:哈哈哈 age:125 sex:男