欢迎光临散文网 会员登陆 & 注册

碎片时间学编程「362]:从左到右执行组合反向撰写功能

2023-07-13 12:27 作者:路条编程  | 我要投稿


执行从左到右的函数组合。  

使用 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

更多内容请访问我的网站:https://www.icoderoad.com


碎片时间学编程「362]:从左到右执行组合反向撰写功能的评论 (共 条)

分享到微博请遵守国家法律