javascript - 请问为什么我的代码不起作用,我需要安装任何库吗

最近开始functional programming,我看到的pipe和compose using reduce的所有解释都非常粗略。

const x = 4

const add2 = x + 2

const multiplyBy5 = x * 5

const subtract1 = x - 1



pipe = (...functions) =>
(x) => functions.reduce((v, function) => function(v), x)

const result = pipe(add2, multiplyBy5, subtract1)(4)
console.log(result)

回答1

有 2 个错误。

  1. 第一个是 xadd2multiplyBy5subtract1 不是函数,而只是定义。
  2. 另一个是您将变量(使用参数)命名为“保留”字的名称,例如“函数”确实破坏了语法解析器。
const x = (x) => x
const add2 = (x) => x+2
const multiplyBy5 = (x) => x*5
const subtract1 = (x) => x-1

const pipe = (...functions) => (x) => functions.reduce((v,fn)=>fn(v),x)
const result = pipe(
  add2,
  multiplyBy5,
  subtract1,
)(4);
console.log(result)

回答2

我认为应该这样做:

const add2 = (x) => x+2
    
const multiplyBy5 = (x) => x*5
    
const subtract1 = (x) => x-1
    
const pipe=(...functions) => (x) => functions.reduce((v, functionA) => functionA(v), x)
    
const result=pipe(add2, multiplyBy5, subtract1)(4)
    
console.log(result)

相似文章

随机推荐

最新文章