科里化

214 阅读1分钟

手写科里化

科里化是解决函数定参问题的一种解决方案,将函数的参数「颗粒化」,支持传递单个参数。 如何没有科里化实现一个函数的加法:

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

使用科里化:

function curry(fn) {
    const args = [];
    return function cb() {
        // 计算结果
        if (arguments.length === 0) {
            let result = fn.apply(this, args);
            return result;
        }
        args.push(...arguments);
        return cb;
    }
}

// 加法
const add = curry(function(){
    return [...arguments].reduce((value, item) => {
        return value + item;
    });
});

// 乘法
const multiply = curry(function() {
    return [...arguments].reduce((value, item) => {
        return value * item;
    });
});

console.log(add(1)(2)(3)(4)(9)()) // 19
console.log((multiply(1)(3, 4))()) // 12