柯里化是将多参数函数转换为单参数函数链,函数组合则是将多个函数串联执行。例如 curry(add)(2)(3) 得 5,compose(toUpper, exclaim)('hi') 得 'HI!'。通过 pipe 或 compose 可构建数据处理流,如 pipe(filter(x => x > 2), map(x => x * 2), reduce((a,b)=>a+b,0))([1,2,3,4,5]) 输出 24。两者结合提升代码复用性与可读性,适用于数据转换、中间件等场景。

柯里化和函数组合是函数式编程中的两个重要概念,它们能帮助我们写出更灵活、可复用的代码。下面分别介绍它们的含义、实现方式以及实际应用场景。
什么是柯里化
柯里化(Currying)是将一个接收多个参数的函数转换为一系列只接受单个参数的函数的过程。每次调用返回一个新的函数,直到所有参数都被传入,最终执行原函数并返回结果。
例如,一个原本需要两个参数的加法函数:
function add(a, b) {
return a + b;
}
可以柯里化为:
立即学习“Java免费学习笔记(深入)”;
function curryAdd(a) {
return function(b) {
return a + b;
};
}
// 使用
const add5 = curryAdd(5);
console.log(add5(3)); // 8
通用柯里化实现: 可以写一个高阶函数来自动柯里化任意函数:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
} else {
return function (...nextArgs) {
return curried.apply(this, args.concat(nextArgs));
};
}
};
}
// 示例
function multiply(a, b, c) {
return a b c;
}
const curriedMultiply = curry(multiply);
console.log(curriedMultiply(2)(3)(4)); // 24
console.log(curriedMultiply(2, 3)(4)); // 24
函数组合的基本原理
函数组合(Function Composition)是指将多个函数连接起来,前一个函数的输出作为后一个函数的输入。数学上表示为:f(g(x))。
在 JavaScript 中,我们可以定义一个组合函数 compose 来实现从右到左的执行顺序:
function compose(...fns) {
return function (value) {
return fns.reduceRight((acc, fn) => fn(acc), value);
};
}
// 示例
const toUpper = str => str.toUpperCase();
const exclaim = str => str + '!';
const sayHello = name => Hello, ${name};
const greet = compose(toUpper, exclaim, sayHello);
console.log(greet('world')); // HELLO, WORLD!
另一种常见的是 pipe,它从左到右执行:
function pipe(...fns) {
return function (value) {
return fns.reduce((acc, fn) => fn(acc), value);
};
}
const greet2 = pipe(sayHello, exclaim, toUpper);
console.log(greet2('world')); // HELLO, WORLD!
柯里化与组合的实际应用
结合柯里化和函数组合,可以让代码更具表达力和可维护性。比如处理数据流时:
// 柯里化工具函数 const map = fn => arr => arr.map(fn); const filter = pred => arr => arr.filter(pred); const reduce = (fn, init) => arr => arr.reduce(fn, init);// 数据处理流水线 const data = [1, 2, 3, 4, 5];
const process = pipe( filter(x => x > 2), map(x => x * 2), reduce((a, b) => a + b, 0) );
console.log(process(data)); // (32)+(42)+(5*2) = 6+8+10 = 24
这种风格让逻辑清晰分离,每个函数职责单一,易于测试和复用。
小结
柯里化让我们能创建预配置的函数,提升复用性;函数组合则帮助我们将简单函数拼装成复杂逻辑。两者结合是函数式编程的核心技巧之一。虽然在日常开发中不必过度使用,但在处理数据转换、中间件、事件处理等场景下非常有用。
基本上就这些,理解原理后可以按需灵活运用。不复杂但容易忽略细节,比如参数个数判断和执行顺序。










