当前位置: 首页 > news >正文

compose、 pipe 组合函数实现

一、compose 的实现:

compose 函数实现详解(函数式编程核心工具)
compose 是函数式编程的核心工具,用于将多个函数组合成从右向左执行的管道。

1. 基础实现(ES5)

function compose(...fns) {return function (initialValue) {return fns.reduceRight((acc, fn) => fn(acc), initialValue);};
}

原理:
reduceRight 从右向左遍历函数数组;
每个函数的输出作为下一个函数的输入;
初始值:initialValue;

2. ES6 箭头函数精简版

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

3. 支持异步函数(Promise)

const asyncCompose = (...fns) => (x) => fns.reduceRight((acc, fn) => acc.then(fn), Promise.resolve(x));

使用示例

// 功能函数
const toUpperCase = str => str.toUpperCase();
const exclaim = str => str + '!';
const reverse = str => str.split('').reverse().join('');// 组合函数
const loudReverse = compose(exclaim, toUpperCase, reverse);console.log(loudReverse('hello')); // "OLLEH!"

执行流程:

原始值: 'hello'
1. reverse('hello')'olleh'
2. toUpperCase('olleh')'OLLEH'
3. exclaim('OLLEH')'OLLEH!'

高级实现(支持多参数初始函数)

function compose(...fns) {return fns.reduce((f, g) => (...args) => f(g(...args)));
}// 使用
const calculate = compose(x => x * 2,        // 第三步:乘2(x, y) => x + y,   // 第二步:加法(x, y) => x * y    // 第一步:乘法
);console.log(calculate(3, 4)); // (3*4)=12 → (12+4)=16 → (16*2)=32

性能优化版(避免嵌套调用栈)

function compose(...fns) {const length = fns.length;return function(...args) {let index = length - 1;let result = fns[index].apply(this, args);while (index--) {result = fns[index].call(this, result);}return result;};
}

优势:
避免递归调用栈溢出
适合组合大量函数 (>1000)

实际应用场景
React 高阶组件

const enhance = compose(withRouter,connect(state => ({ user: state.user })),withStyles(styles)
);
export default enhance(Component);

数据处理管道

const cleanData = compose(removeDuplicates,filterInvalidRecords,normalizeDates
);const report = cleanData(rawDataset);

中间件链(Redux/Koa)

// Koa-style middleware
const app = compose(middleware1,middleware2,controller
);

Lodash 对应实现:_.flowRight
Ramda 对应实现:R.compose

设计要点
函数顺序:从右向左执行(数学函数组合标准)
数据流向:前一函数的输出 = 后一函数的输入
纯函数要求:所有组成函数应为纯函数
参数要求:除最右函数外,其它函数应接收单参数

二、pipe 函数

pipe 用于将多个函数组合成从左向右执行的管道。

实现方式:从左向右的 pipe(与 compose 方向相反)

// compose(f, g, h)(x) = f(g(h(x)))
// pipe(h, g, f)(x) = f(g(h(x))) const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);

文章转载自:
http://aws.wjrtg.cn
http://aliform.wjrtg.cn
http://baboon.wjrtg.cn
http://agape.wjrtg.cn
http://catechetics.wjrtg.cn
http://armoric.wjrtg.cn
http://cartilage.wjrtg.cn
http://borazon.wjrtg.cn
http://bugloss.wjrtg.cn
http://calcinator.wjrtg.cn
http://authigenic.wjrtg.cn
http://ascension.wjrtg.cn
http://centric.wjrtg.cn
http://carbonado.wjrtg.cn
http://caldron.wjrtg.cn
http://araeosystyle.wjrtg.cn
http://altitudinal.wjrtg.cn
http://carnal.wjrtg.cn
http://checkerberry.wjrtg.cn
http://chaunt.wjrtg.cn
http://balladry.wjrtg.cn
http://bonnily.wjrtg.cn
http://accumulative.wjrtg.cn
http://cerebratmon.wjrtg.cn
http://additory.wjrtg.cn
http://blueprint.wjrtg.cn
http://accelerative.wjrtg.cn
http://appropriator.wjrtg.cn
http://chromatology.wjrtg.cn
http://autogamous.wjrtg.cn
http://www.dtcms.com/a/281043.html

相关文章:

  • 20th Day| 235.二叉搜索树的最近公共祖先,701.二叉搜索树中的插入操作, 450.删除二叉搜索树中的节点
  • Postman + Newman + Jenkins 接口自动化测试
  • 使用canal同步分库分表数据,到 Elasticsearch
  • JavaScript事件
  • 【数据同化案例1】ETKF求解 Lorenz-63 模型的同化系统(完整MATLAB实现)
  • Java-特殊文件、日志技术
  • CherryStudio配置DeepSeek调用MCP服务实现任务自动化
  • Elasticsearch 9.x 搜索执行过程(源码解析)
  • AOP简化MyBatis分页:高效自动化方案
  • 第二十篇 Word文档自动化:Python批量生成、模板填充与内容修改,告别繁琐排版!
  • Web3 支付系统:面向企业和消费者的全面概述
  • 时间序列挖掘及建模
  • Linux系统集群部署模块之Keepalived双机热备
  • 使用SQLMAP的文章管理系统CMS的sql注入渗透测试
  • Java全栈工程师面试实录:从电商系统到AIGC的层层递进
  • WSF70N10G N 沟道 MOSFET 在蓝牙耳机中的应用分析
  • Linux获取CPU/GPU的温度
  • docker部署gbase8s(数据持久化)并用可视化工具管理
  • NuGet01-安装及使用
  • gRPC实战指南:像国际快递一样调用跨语言服务 —— 解密Protocol Buffer与HTTP/2的完美结合
  • 【GPIO】从STM32F103入门GPIO寄存器
  • Video Python(Pyav)解码一
  • 面试150 完全二叉树的节点数
  • 力扣73:矩阵置零
  • 20250715_Sneak_neuro 靶机复盘
  • 三种深度学习模型(LSTM、CNN-LSTM、贝叶斯优化的CNN-LSTM/BO-CNN-LSTM)对北半球光伏数据进行时间序列预测
  • 【15】MFC入门到精通——MFC弹窗提示 MFC关闭对话框 弹窗提示 MFC按键触发 弹窗提示
  • C++(STL源码刨析/stack/queue/priority_queue)
  • Linux操作系统之信号:保存与处理信号
  • 23种设计模式--#1工厂模式