-2

while reading about reduce in mdn , i am struck up with following code.

// Building-blocks to use for composition
const double = (x) => 2 * x;
const triple = (x) => 3 * x;
const quadruple = (x) => 4 * x;

// Function composition enabling pipe functionality
const pipe =
  (...functions) =>
  (initialValue) =>
    functions.reduce((acc, fn) => fn(acc), initialValue);

// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);

// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240

can you please explain the code detailly as step by step which is helpful for me for more understanding and I am curious about how the function knows the initial value .

  • 1
    Please see https://stackoverflow.com/help/how-to-ask – Ingo Steinke Dec 13 '22 at 11:36
  • Try using your browser’s [debug capabilities](//ali-dev.medium.com/how-to-easily-debug-in-javascript-5bac70f94f1a). See [What is a debugger and how can it help me diagnose problems?](/q/25385173/4642212). In other words: _“can you please explain the code detailly as step by step”_ — Why would you ask _us_ if _you_ have _automated_ tools built into the browser _you’re using right now_ that do this sort of thing _automatically_? Have you read the [documentation](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)? – Sebastian Simon Dec 13 '22 at 11:41
  • If you’re confused about the syntax, see [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Dec 13 '22 at 11:42

1 Answers1

1

Pipe is an operation that accepts zero or more functions and returns a function that invokes those functions in a "chain", passing the result of each function to the next. So multiply6 will be a function that invokes double against initialValue, and then passes the result of this to triple (hence "multiply6").

const pipe = // pipe is a 
  (...functions) => // ...function that accepts zero or more functions,
  (initialValue) =>  // ...that returns a function accepting one initial value,
    functions.reduce((acc, fn) => fn(acc), initialValue) // ...that enumerates `functions`, invoking each, passing the result to the next
Ben Aston
  • 53,718
  • 65
  • 205
  • 331