当前位置:首页 > JavaScript

js实现compose

2026-02-01 04:24:43JavaScript

js实现compose

实现 compose 函数的方法

在 JavaScript 中,compose 函数用于将多个函数组合成一个新的函数,新函数的执行顺序是从右到左。以下是几种实现 compose 的方法:

js实现compose

使用 reduce 实现

const compose = (...fns) => 
  fns.reduce((f, g) => (...args) => f(g(...args)));

递归实现

const compose = (...fns) => {
  const [first, ...rest] = fns.reverse();
  return (...args) => rest.reduce((res, fn) => fn(res), first(...args));
};

使用 reduceRight 实现

const compose = (...fns) => 
  fns.reduceRight((prevFn, nextFn) => 
    (...args) => nextFn(prevFn(...args))
  );

示例用法

const add5 = x => x + 5;
const multiply2 = x => x * 2;
const subtract3 = x => x - 3;

const composedFn = compose(subtract3, multiply2, add5);
console.log(composedFn(5)); // 输出: (5 + 5) * 2 - 3 = 17

实现 pipe 函数的方法

pipe 函数与 compose 类似,但执行顺序是从左到右。以下是实现方式:

使用 reduce 实现

const pipe = (...fns) => 
  fns.reduce((f, g) => (...args) => g(f(...args)));

示例用法

const pipedFn = pipe(add5, multiply2, subtract3);
console.log(pipedFn(5)); // 输出: ((5 + 5) * 2) - 3 = 17

注意事项

  • composepipe 的区别在于函数的执行顺序。
  • 确保传入的函数参数是可执行的,否则会抛出错误。
  • 可以结合箭头函数和剩余参数(...)简化实现。

标签: jscompose
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…

js实现下拉菜单

js实现下拉菜单

使用HTML和CSS创建基础结构 HTML部分需要包含一个触发下拉的按钮和隐藏的下拉菜单内容: <div class="dropdown"> <button class="dr…