Extending Lo Dash With More Methods

January 15, 2015    js javascript lodash

Lo-Dash is the go to JavaScript utility library for any project, atleast for me. Whats really cooler is that you can extend it with more methods if the ones already available are working out for ya.

The creators of Lo-Dash made sure to build a method in to the library to do just that. I'll be extending the library to create a method that returns a random element from an Array.

_.mixin({ randElement: function (arr) {  
    if (arr instanceof Array) {  
        var randElem = arr[Math.floor(Math.random() * arr.length)];  
        return randElem;  
    }  
}});  

You can now use the method like so

_.randElement([1,2,3]);  
// 2  

Update

John-David Dalton, one of the contributors to Lo-Dash, sent in a great tip. Lo-Dash has a _.runInContext() method which creates a pristine lodash function with a given ‘context’ object. This comes in handy if you're building a library and want to avoid conflicts in the code.

So, for the function we defined in this post, we can re-define it using the context method.

var lodash = _.runInContext();  
lodash.mixin({ randElement: function (arr) {...}});  

We can use this method by invoking lodash.randElement([1,2,3])



comments powered by Disqus