JavaScript函数式编程_柯里化与组合技巧

柯里化将多参函数转化为单参函数链,实现参数预配置;组合通过compose或pipe串联函数,提升代码复用与可读性;二者结合可构建清晰的数据处理流程。

在JavaScript函数式编程中,柯里化(Currying)组合(Composition) 是两个非常实用的技巧。它们能帮助我们写出更简洁、可复用、易于测试的代码。下面直接来看这两个概念的实际意义和使用方法。

什么是柯里化

柯里化是把一个接收多个参数的函数转换成一系列只接受一个参数的函数的过程。每次调用返回一个新的函数,直到所有参数都被传入。

比如有一个加法函数:

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

// 柯里化后:
const curriedAdd = a => b => c => a + b + c;

curriedAdd(1)(2)(3); // 6

这种写法的好处是你可以“预配置”部分参数:

const addOne = curriedAdd(1);
addOne(2)(3); // 6
addOne(5)(10); // 16

这在处理通用逻辑时特别有用,比如过滤数组:

const greaterThan = threshold => num => num > threshold;

const isPositive = greaterThan(0);
[−1, 0, 1, 2].filter(isPositive); // [1, 2]

如何实现通用柯里化函数

我们可以写一个函数,自动将普通函数转换为柯里化版本:

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);
curriedMultiply(2)(3)(4); // 24
curriedMultiply(2, 3)(4); // 24

这个 curry 函数通过判断参数个数决定是否继续返回新函数,兼容多种调用方式。

函数组合:把小函数拼成大功能

组合(compose)是指将多个函数连接起来,前一个函数的输出作为下一个函数的输入。这是函数式编程的核心思想之一。

比如我们有两个函数:

const toUpper = str => str.toUpperCase();
const exclaim = str => str + '!';

// 组合它们:
const shout = str => exclaim(toUpper(str));
shout('hello'); // 'HELLO!'

但如果函数多了,嵌套会变得难读。我们可以写一个 compose 工具函数:

const compose = (...fns) => value =>
  fns.reduceRight((acc, fn) => fn(acc), value);

// 从右往左执行
const shout = compose(exclaim, toUpper);
shout('hello'); // 'HELLO!'

还有一个方向叫 pipe,从左到右执行,更符合阅读习惯:

const pipe = (...fns) => value =>
  fns.reduce((acc, fn) => fn(acc), value);

const scream = pipe(toUpper, exclaim);
scream('hi'); // 'HI!'

组合让代码更声明式,也更容易测试每个小函数。

柯里化与组合结合使用

真正强大的地方在于把柯里化和组合一起用。比如处理数据流:

const map = fn => array => array.map(fn);
const filter = fn => array => array.filter(fn);
const prop = key => obj => obj[key];

// 示例数据
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

// 获取所有用户的名字
const getNames = pipe(
  map(prop('name'))
);

getNames(users); // ['Alice', 'Bob', 'Charlie']

// 获取年龄大于30的用户名字
const getElderNames = pipe(
  filter(user => user.age > 30),
  map(prop('name'))
);

getElderNames(users); // ['Charlie']

这种风格清晰、可复用,而且每个函数都很小,容易单元测试。

基本上就这些。柯里化让你“记住”部分参数,组合让你像搭积木一样构建逻辑。两者配合,JavaScript函数式编程会变得更优雅。不复杂但容易忽略。