JS: Function Pipe 🚀

By Xah Lee. Date: . Last updated: .

Here is a function to Pipe Functions similar to shell pipe operator x | y | z. (aka, Function Chaining, Postfix Function Composition,)

/*
   xah_pipe(x) → x
   xah_pipe(x,f) → f(x)
   xah_pipe(x,f,f2) → f2(f(x))
   xah_pipe(x,f,f2,f3) → f3(f2(f(x)))
   etc

   URL http://xahlee.info/js/js_function_chaining.html
   Created 2016
   Version 2022-10-14
*/

const xah_pipe = ((...xargs) => xargs.reduce((a, b) => b(a)));

// ssss---------------------------------------------------

// test

const fa = ((x) => (x + "a"));
const fb = ((x) => (x + "b"));
const fc = ((x) => (x + "c"));

console.log(xah_pipe("0") === "0");
console.log(xah_pipe("0", fa) === "0a");
console.log(xah_pipe("0", fa, fb) === "0ab");
console.log(xah_pipe("0", fa, fb, fc) === "0abc");

See also: Functional Programing

JavaScript, Function

JavaScript, Array Reduce, Fold

BUY ΣJS JavaScript in Depth