JS compose 函数实现
JS 实现 函数 Compose
2023-09-14 09:07:43 时间
两种实现方案
实现原理:
1. 如果传入的 function 为空,则直接返回 参数数组
2. 如果传入的 function 只有一个,则直接调用第一个
3. 否则从右向左依次执行
4. 原理为:compose中传入多个函数,会依次从右向左执行,将右面函数的执行结果作为参数传入左边一个函数中
// 方式一 function compose(...funcs) { let length = funcs.length; if (length === 0) { return (...args) => args; } if (length === 1) { return funcs[0]; } return funcs.reduce((a, b) => { return (...args) => { return a(b(...args)); }; }); } // 方式二 function compose(...funcs) { //=>funcs:传递的函数集合 return function proxy(...args) { //=>args:第一次调用函数传递的参数集合 let len = funcs.length; if (len === 0) { //=>一个函数都不需要执行,直接返回ARGS return args; } if (len === 1) { //=>只需要执行一个函数,把函数执行,把其结果返回即可 return funcs[0](...args); } return funcs.reduceRight((x, y) => { return typeof x === "function" ? y(x(...args)) : y(x); }); // return funcs.reverse().reduce((x, y) => { // return typeof x === "function" ? y(x(...args)) : y(x); // }); }; } // 方式三: // 递归 function compose(...funcs) { if (funcs.length === 0) { return (...args) => args; } if (funcs.length === 1) { return funcs[0]; } let count = funcs.length - 1; let result = undefined; return function fn(...args) { if (count < 0) { return result; } result = funcs[count--](...args); return fn(result); }; } const fn1 = (x) => x + 10; const fn2 = (x) => x * 10; const fn3 = (x) => x - 10; console.log(compose(fn3, fn2, fn1)(1)); // 100 console.log(compose()(1)); // [1] console.log(compose(fn1)(1)); // 11
参考链接 https://blog.csdn.net/MRlaochen/article/details/120437542
https://www.bilibili.com/video/BV1h5411N7eq?p=2&vd_source=194f8fed26c3607cae375c20d6e308f0
相关文章
- JS自定义编码和解码方案
- JS实现图片懒加载
- <转载> js 闭包
- 纯js实现人脸识别眨眨眼张张嘴案例——ccv.js
- [Node.js] Using npm link to use node modules that are "in progress"
- JS实现密码加密
- MUI导航栏透明渐变----原生JS实现
- js操作节点对象注意事项
- SAP UI5 walkthrough 8 - how is component.js loaded
- Atitit 文件上传 架构设计 实现机制 解决方案 实践java php c#.net js javascript c++ python
- Atitit. Java script 多重多重catch语句的实现and Javascript js 异常机制
- js随机飘动的广告图片代码demo效果示例(整理)
- 前端js实现打印(导出)excel表格
- vuejs项目纯js导出word、在线下载富文本内容或者网页另存为word文件
- leetcode 234. 回文链表 js 实现
- leetcode 78. 子集 js 实现
- js实现 once 方法
- js实现 delay 和 sleep函数
- js和css实现手机横竖屏预览思路整理
- js之瀑布流的实现
- 华为校招机试 - 简单的自动曝光、平均像素值(Java & JS & Python)
- js时间戳转时间