我最近尝试了解javascript中的函数组成。我了解了什么是currying以及它是如何工作的,但是我看到了这段代码,但我并没有真正理解它。使用.reduce(...)
进行功能合成。这是代码:
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
const add5 = x => x + 5;
const add10 = x => x + 10;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = compose(
add10,
add5,
multiply
);
console.log(multiplyAndAdd5(5, 2));
我不了解的是reduce函数,我试图将其分解为::>
中显示:const compose = (...fns) => fns.reduce( (f, g) => (...args) => { console.log("f: "); console.log(f); console.log("g: "); console.log(g); for(let i = 0 ; i < 3 ; i++){ console.log(''); } return f(g(...args)) }, );
在控制台
在该函数中的实际含义,在reduce函数的第一部分中,f是函数本身,所以f(g( ... args))在这种情况下?f: (...args) => { console.log("f: "); console.log(f); console.log("g: "); console.log(g); // console.log("args: "); // console.log(...args); // console.log(f(g(...args… g: (x, y) => x * y f: x => x + 10 g: x => x + 5 15 25
我不理解的是accumulator
有人知道如何使用。reduce()
在JavaScript中进行功能组合吗?我最近尝试了解javascript中的函数组成。我了解了什么是currying以及它是如何工作的,但是我看到了这段代码,但我并不太了解。它是使用...
reduce
可以被认为是将运算符放在序列中每对项目之间。例如。使用[1, 2, 3]
还原*
会产生1*2*3
(通过执行((1)*2)*3)
;以相同的方式,使用函数组成进行还原会将[f, g, h]
还原为f∘g∘h
(通过执行((f∘g)∘h)
,也写为(...args) => f(g(h(...args)))
]。