-3

Recently started functional programming and all explanations of the pipe and compose using reduce which I have seen are very sketchy.


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)

Maharramoff
  • 941
  • 8
  • 15
  • Try adding ";" at the end of every line. Since this is javascript, you need to add it. I am not sure if this will fix your problem, but it is an error. – FairOPShotgun May 14 '22 at 22:58
  • 3
    @FairOPShotgun semicolons are not necessary except in certain ambiguous situations. see: [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi) – pilchard May 14 '22 at 23:08

2 Answers2

3

There were 2 errors.

  1. The first one was that the x, add2, multiplyBy5 and subtract1 were not functions, but mere definitions.
  2. The other was that you naming a variable (using the arguments) to a name that is a "reserved" word such as "function" did break the syntax parser.

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)
Akxe
  • 9,694
  • 3
  • 36
  • 71
  • 1
    Btw, we can leave the first one as the definition :) – Maharramoff May 14 '22 at 23:17
  • Thanks a lot.What is most annoying is that ,the initial code I wrote with the whole fns and fn started working.It was showing an error ,the reason I changed it but right now it is working – Steve purpose May 15 '22 at 06:15
0

I think it should be done like this:

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)
Vladimir Posvistelik
  • 3,843
  • 24
  • 28