Lo-dash: Augment lodash with custom functions

Add your own custom methods or extend existing ones with custom behaviour

Posted by Aditya Pratap Singh on September 7, 2015

Lo-dash provides a whole stack of cross-environment utility functions and focuses on performance aspects in javascript which is the key reason of high adoption of lo-dash. But, at times the given set of utilities appear constrained for our usage. In such scenarios, we may want to update the existing method or add a new one to solve our purpose.

Let us take one such scenario and create a new function $upsert which mutates an array and update a given object in array based on passed criterion. This is a common scenario and to use this, we may have to create a function such as below and call it everytime using _.bind :

JS Bin on jsbin.com


A much better way is to add this method being called as part of the lo-dash library and use it on _ object. Lo-dash provides a method _.mixin for this. Let us see how we can use the above code to create the mixin and use it conveniently and even on function chains.

JS Bin on jsbin.com

That's it! Using the same _.mixin method we can even decorate/ augment existing library methods. But, we should be cautious in doing so as it may have unwanted side-effects on parts of our code.