从左到右组合函数

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将探讨 JavaScript 中函数组合的概念。具体来说,我们将重点关注 composeRight 函数,它使我们能够将多个函数组合成一个从左到右执行的单一函数。通过实际示例,我们将看到函数组合如何简化我们的代码并使其更具模块化。

反转函数组合

要开始练习编码,请打开终端/SSH 并输入 node

以下是如何进行从左到右的函数组合:

  • 使用 Array.prototype.reduce() 方法进行从左到右的函数组合。
  • 第一个(最左边的)函数可以接受一个或多个参数,而其余函数必须是一元函数。
const composeRight = (...fns) =>
  fns.reduce(
    (f, g) =>
      (...args) =>
        g(f(...args))
  );

例如:

const add = (x, y) => x + y;
const square = (x) => x * x;
const addAndSquare = composeRight(add, square);
addAndSquare(1, 2); // 9

总结

恭喜你!你已经完成了“反转组合函数”实验。你可以在 LabEx 中练习更多实验来提升你的技能。