Wednesday, October 9, 2013

Chaining calls with Underscore.js

I have came across underscore ( — a wonderful collection of javascript functions making one’s life easier — a while ago.
However, I have only recently found out that underscore.js has a beautiful interface of chaining. The samples below are quite self-descriptive for anyone familiar with javascipt. But anyway, idea is that with chaining, underscore would automatically pass the result of the previous operation to the next one.
That’s how the work looks w/out chaining:
var someData = [1,4,2,4,5,6];
var results =
      _.sortBy(someData, _.identity),
      function(a) {return a>3}),
   function(m) {return m*m}
//outputs [16, 16, 25, 36]
and that’s how it looks like when we use method chaining:
var someData = [1,4,2,4,5,6];
var results = _.chain(someData)
   .filter(function(a){return a>3})
   .map(function(m){return m*m})
   .value(); // that's the piece which 'executes' the chain
//outputs [16, 16, 25, 36]
You judge which one is better!

No comments: