JavaScript 从浅入深 100 题训练计划--(15)函数组合(Compose & Pipe)-reduce函数介绍
题目:实现 compose 和 pipe
// compose: 从右到左
compose(f, g, h)(x) === f(g(h(x)))
// pipe: 从左到右
pipe(f, g, h)(x) === h(g(f(x)))
相关知识点reduce函数:reduce函数介绍(1) - 小新的蜡笔 - 博客园
1 function compose(...fns) { 2 return function (...args) { 3 return fns.reduceRight((acc, cur) => { 4 return Array.isArray(acc) ? cur(...acc) : cur(acc) 5 }, args) 6 } 7 } 8 function pipe(...fns) { 9 return function (...args) { 10 return fns.reduce((acc, cur) => { 11 return Array.isArray(acc) ? cur(...acc) : cur(acc) 12 }, args) 13 } 14 } 15 16 // 辅助函数 17 const add = x => x + 1; 18 const multiply = x => x * 2; 19 const square = x => x * x; 20 21 // compose: 从右到左 (square(multiply(add(5)))) = square(multiply(6)) = square(12) = 144 22 const composed = compose(square, multiply, add); 23 console.log(composed(5), 'composed'); // 144 24 // pipe: 从左到右 (square(multiply(add(5)))) 注意顺序相反 25 const piped = pipe(add, multiply, square); 26 console.log(piped(5)); // 144

浙公网安备 33010602011771号