1 Star 0 Fork 0

laddish/functional-program-learning

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
pipe-compose.js 1.28 KB
一键复制 编辑 原始数据 按行查看 历史
laddish 提交于 2021-07-26 10:48 . 练习
function add(a, b) {
return a + b;
}
function square(a) {
return a * a;
}
function plusOne(c) {
return c + 1;
}
// const pipe = (...args) => {
// return (...arguments) => {
// const init = args[0].apply(null, arguments);
// return args.slice(1).reduce((memo, current) => {
// return current(memo);
// }, init);
// };
// };
const pipe = (...args) => {
//接收多个函数
return (...arguments) => {
return args.reduce((memo, current) => {
//第一个参数是前一个执行的返回值
//第二个参数是当前的函数
//把当前函数的执行返回值给下一个函数
//reduce过程中不停的执行
return current(
typeof memo === "function" ? memo.apply(memo, arguments) : memo
);
});
};
};
const compose = (...args) => {
return (...arguments) => {
return args.reduceRight((memo, current) => {
return current(
typeof memo === "function" ? memo.apply(memo, arguments) : memo
);
});
};
};
var addSquareAndPlusOneCompose = compose(plusOne, square, add);
var addSquareAndPlusOne = pipe(add, square, plusOne);
// function composite(add, square, plusOne) {
// return function () {};
// }
// console.log(addSquareAndPlusOne(1, 2));
console.log(addSquareAndPlusOneCompose(1, 2));
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/laddish/functional-program-learning.git
git@gitee.com:laddish/functional-program-learning.git
laddish
functional-program-learning
functional-program-learning
master

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385