JavaScript: Function Pipe

By Xah Lee. Date: . Last updated: .

Here is a function to Pipe Functions instead of Method Chaining.

In JavaScript, we can do method chaining. That is, the dotted syntax:

x.f().f2().f3()

This works because:

  1. the value of x is a object and has a method f.
  2. the value of x.f() is a object and has a method f2.
  3. the value of x.f().f2() is a object and has a method f3.

If you want to write a library that allow method chaining, just make sure your methods all return the same object X of your lib, and all the methods are properties of X.

Method chaining can be considered as a postfix notation. For example, similar to unix pipe x | f | f2 | f3.

The problem with method chaining is that it relies on the fact that the preceding sequence must return a object that has the next method as property.

You cannot chain functions A and B with the dot notation if A and B has no object/property relation.

However, you can write a function that does this.

Postfix Function Composition

Here is a way to chain functions without them being a property of the return object.

  1. xah_pipe(x) ⇒ x
  2. xah_pipe(x,f) ⇒ f(x)
  3. xah_pipe(x,f,f2) ⇒ f2(f(x))
  4. xah_pipe(x,f,f2,f3) ⇒ f3(f2(f(x)))
  5. etc
/* [
   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

   http://xahlee.info/js/js_function_chaining.html
   Created 2016
   Version 2018-05-09 2021-06-26
] */
const xah_pipe = (( ...rest) => {
    let ff = Array.prototype.shift.call ( rest);
    while ( rest.length > 0) { ff = (Array.prototype.shift.call( rest))(ff); }
    return ff;
});
// 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" );
// all true

See also: Functional Programing

JavaScript Function

BUY
ΣJS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc