JavaScript绑定应在未定义的情况下将第二个参数设置为等于第一个参数?

问题描述 投票:0回答:1

我最近尝试了解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))
  },
);

控制台

中显示:
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函数的第一部分中,f是函数本身,所以f(g( ... args))在这种情况下?

有人知道如何使用。reduce()

在JavaScript中进行功能组合吗?

我最近尝试了解javascript中的函数组成。我了解了什么是currying以及它是如何工作的,但是我看到了这段代码,但我并不太了解。它是使用...

javascript reduce function-composition
1个回答
2
投票

reduce可以被认为是将运算符放在序列中每对项目之间。例如。使用[1, 2, 3]还原*会产生1*2*3(通过执行((1)*2)*3);以相同的方式,使用函数组成进行还原会将[f, g, h]还原为f∘g∘h(通过执行((f∘g)∘h),也写为(...args) => f(g(h(...args))) ]。

© www.soinside.com 2019 - 2024. All rights reserved.