I am reading a book called Learning React, 2nd Edition. There's a section about function composition under functional programming section. The code snippet and explanation provided are not super clear to me. Here's the code snippet from the book -


Here's the above code in code snippet -
const both = compose(
civilianHours,
appendAMPM
):
both(new Date());
const compose = (...fns) => arg =>
fns.reduce((compose, f) => f(composed), arg);
I don't understand what the author is trying to explain here. Here's the explanation provided from the book for this snippet.
The compose function is a higher-order function. It takes functions as arguments and returns a single value. compose takes in functions as arguments and returns a single function. In this implementation, the spread operator is used to turn those function arguments into an array called fns . A function is then returned that expects one argument, arg . When this function is invoked, the fns array is piped starting with the argument we want to send through the function. The argument becomes the initial value for compose , then each iteration of the reduced callback returns. Notice that the callback takes two arguments: composed and a function f . Each function is invoked with compose , which is the result of the previous function’s output. Eventually, the last function will be invoked and the last result returned.
So can anyone explain to me how function piping works in javascript with some examples? It would be nice if someone could explain the above code snippet too. Especially what the arg is doing sitting over there.
Here's another code snippet for the same question -
const add2 = (x) => x + 2;
const subtract1 = (x) => x - 1;
const multiplyBy5 = (x) => x * 5;
const pipe = (...fns) => (val) => fns.reduce((prev, fn) => fn(prev), val);
const pipeResult = pipe(add2, subtract1, multiplyBy5)(5);
console.log(pipeResult); // = 30