Chaining in Underscore.js
This one is from the archives. Enjoy! 22 Feb 13 @ 20:14
The Underscore library gives you a choice of programming style: functional VS. chaining. Under the right circumstances, I think chaining can lead to more readable code.
To demonstrate, lets clean up a very ‘dirty’ array using the two methods in Underscore.js Here is the array we will be working with:
let lottery = [ 1, 2, 3, '', 1, 4, null, [ 7, 6, 5, ], 33, 55, 3204, 463 ]
The “Functional” Way
let unique = _.uniq(flattened); let compacted = _.compact(unique); let result = compacted;
This is how most beginners will approach this problem (with or without the help of underscore). Notice how we have to declare many variables that will only be used once, and the subsequent line must contain the variable created in the previous line passed in as an argument.
This can become an issue if we need to reorder the process because we would need to make sure we are passing in the previous variable created.
Lets try to rewrite this using the cleaner, chainable approach.
The Chainable way
let result = _.chain(lottery) .flatten() .uniq() .compact() .value()
When we start with the .chain method, we are telling underscore to return a wrapped object (rather than just the result) that allows us to continue modifying the results with other underscore methods.
Once we’re finished making changes to the array, we simply chain .value to the end to get the final result. Benefits
- We can be much more explicit here with out saying as much.
- We also don’t pollute the namespace with all the extra variables.
- We don’t use as much memory because we aren’t storing any extra data.
- We don’t need to leave as many comments because the code reads almost like plain English.
That’s all folks
If you have any questions or comments, feel free to ask below!