Two Turn Tables and a Mixin

Blog
The best minds from Teradata, our partners, and customers blog about whatever takes their fancy.
Teradata Employee

This blog entry provides a brief introduction to underscore.js mixins.

Introduction

If you are not using underscore.js then I feel sorry for your code base. Underscore.js abstracts a lot of common routines and delegates to corresponding ES5 methods if they exist. It makes your life much easier and reduces noise in your code. Underscore.js also gives you the ability to create your own underscore.js functions in addition to the great ones included with underscore.js. Why is this good and please provide me with a use case.

Example

I don’t know about you, but I am sick of writing and reading code like this.

if (obj && obj.prop1 && obj.prop1.prop2 && obj.prop1.prop2 === 42)
doSomethingCool();

Underscore.js to the rescue, https://gist.github.com/2473110. Now we can simly write the following.

if (_.validChain('obj.prop1.prop2', 42))
doSomethingCool();

If you do not pass a truth test argument (42 in this case) then _.validChain() will return a boolean indicating whether or not the structure is valid. You can also pass a function as the truth test argument, e.g., function (test) { return 52 - 10 === test }.

Closing

Hopefully the code above speaks for itself. If not then try reading it again. Seriously though if it doesn't make sense or you feel that my approach is awful then comment on the gist, https://gist.github.com/2473110