我在研究管道函数时遇到了这个将 _pipe 函数作为参数的 reduce 函数。 _pipe 函数有两个参数 a,b,然后返回另一个函数。
reduce 在这里如何工作?
add3 = x => x + 3;
add5 = x => x + 5;
const _pipe = (a, b) => (arg) => b(a(arg))
const pipe = (...ops) => ops.reduce(_pipe)
const add = pipe(add3, add5)
add(10)
输出 18
最佳答案
查看管道函数定义:
const pipe = (...ops) => ops.reduce(_pipe)
它接收称为 ops 的函数数组(称为 rest params )。 然后我们为 ops 数组调用 reduce。 Reducer 函数有 2 个参数:累加器和当前值。
这是我们用人类可读变量编写的 _pipe:
const _pipe = (accumulator, currentValue) => (arg) => currentValue(accumulator(arg));
因此 _pipe 的结果将是来自 ops 数组的柯里化(Currying)函数。
如果是 [add3, add5] 那么结果将是 (arg) => add3(add5(arg))
如果它是 [add3, add5, add2] 那么结果是: (arg) => add2(accumulator(arg)) 其中累加器是 (arg) => add3(add5(arg))。
您只需使用 reduce 组合数组中的所有函数。然后传入初始值10。
就像:add3(add5(10)) = 18
关于javascript - 在这种情况下如何减少工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943666/