执行从左向右的函数组合

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

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

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

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

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8