Chris
Chris

Reputation: 58182

How to create (optionally) chainable functions like in Lodash?

A common, and very readable, pattern found in Lodash is "chaining". With chaining, the result of the previous function call is passed in as the first argument of the next.

Such as this example from Lodash docs:

var users = [
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 }
];

// A sequence with chaining.
_(users)
  .head()
  .pick('user')
  .value();

head and pick can both be used outside of a chain as well.

Going through the source, there is nothing obviously special about the actual methods being called in the chain - so it must be linked to either the initial _ call and/or value call.

Head: https://github.com/lodash/lodash/blob/4.11.0/lodash.js#L6443 Pick: https://github.com/lodash/lodash/blob/4.11.0/lodash.js#L12598

How does one achieve this pattern with their own methods? And does it have a term?

An example might be:

const house = 
    this
        .addFoundation("concrete")
        .addWalls(4)
        .addRoof(true)
        .build();

// Functions being (each can be called by manually as well)

addFoundation(house, materialType) { ... }
addWalls(house, wallCount) { ... }
addRoof(house, includeChimney) { ... }

// And..
build() // The unwrapped method to commit the above

Upvotes: 0

Views: 646

Answers (2)

BrunoLM
BrunoLM

Reputation: 100331

One example on how to do it

function foo(arr) {
  if (!(this instanceof foo)) {
    return new foo(arr);
  }

  this.arr = arr;
  return this;
}


foo.prototype.add = function(p) {
  this.arr.push(p);
  return this;
}

foo.prototype.print = function() {
  console.log(this.arr);
  return this;
}

foo([1, 2]).add(3).print();

Say you want to do this as well

foo.add(3).print();

You need to create a method on foo (not the prototype)

foo.add = function(p) {
  return foo([p]);
}

foo.add(3).print() // [3]

Upvotes: 2

Crhistian
Crhistian

Reputation: 1272

It's called method chaining. Here's two articles on it. The basic gist of it is that you return the current object at the end of the function.

http://schier.co/blog/2013/11/14/method-chaining-in-javascript.html

http://javascriptissexy.com/beautiful-javascript-easily-create-chainable-cascading-methods-for-expressiveness/

Upvotes: 1

Related Questions