执行从右向左的函数组合

5年以前  |  阅读数:362 次  |  编程语言:JavaScript 

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

使用Array.reduce()执行从右向左的函数组合。最后一个 (最右边) 的函数可以接受一个或多个参数;其余的函数必须是一元的。

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
/*
const add5 = x => x + 5
const multiply = (x, y) => x * y
const multiplyAndAdd5 = compose(add5, multiply)
multiplyAndAdd5(5, 2) -> 15
*/

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8