JS: Function Chaining

By Xah Lee. Date: . Last updated: .

Here's 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's a way to chain functions without them being a property of the return object.

  1. pipe(x) ⇒ x
  2. pipe(x,f) ⇒ f(x)
  3. pipe(x,f,f2) ⇒ f2(f(x))
  4. pipe(x,f,f2,f3) ⇒ f3(f2(f(x)))
const pipe = (( ...rest) => {

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

   http://xahlee.info/js/js_function_chaining.html
   version 2018-05-09
) */

    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( pipe("0") === "0" );
console.log( pipe("0", fa) === "0a" );
console.log( pipe("0", fa, fb) === "0ab" );
console.log( pipe("0", fa, fb, fc) === "0abc" );
// all true

See also: JS: Functional Programing

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials