Tag Archives: mixins

LoDash.js / Underscore.js mixins

Here are a few mixins I’ve created for LoDash.js I’ve found handy.

_.getDeep

/**
* Safely retrieves the value of a deeply nested object value
* @param {object} O The Object to be searched
* @param {string} str Dot notation string of the address of the attribute to be retrieved
* @return {mixed} Value of nested item or undefined
* @link http://stackoverflow.com/a/15400575/417822
*/
_.mixin({'getDeep': function(O, str) {
if ( !_.isObject(O) ) return;

var seg= str.split('.');
while(O && seg.length) {
O = O[seg.shift()];
}
return O;
}});

_.hasDeep

/**
* Tests if a deep value has a value/exists. Uses _.getDeep to retrieve value.
* @param {object} O The Object to be tested
* @param {string} str Dot notation string of the address of the attributed to be tested
* @return {boolean}
* @todo validate that falesy values 'false' '0' etc come back as true.
*/
_.mixin({'hasDeep': function(O, str) {
return !_.isUndefined( _.getDeep(O, str) );
}});

_.isDefined
Because typing !_.isUndefined() all the time is tiresome. Using _.isDefined is clear and more readable.

/**
* Shorthand for !_.isUndefined
* @param {mixed} e Item to be tested
* @return {boolean}
*/
_.mixin({'isDefined': function(e) {
return !_.isUndefined(e);
}});

_.compactObject

/**
* Removes all falsy and undefined values from an object
* @param {object} o Object to be compacted
* @return {object} Compact Object
* @link http://stackoverflow.com/a/14058408/417822
*/
_.mixin({'compactObject': function(o) {
var clone = _.clone(o);

_.each(clone, function(v, k) {
if(!v) delete clone[k];
});

return clone;
}});

_.compactObject

/**
* Toggles an array element
* @param {Array} arr Source Array
* @param {Mixed} val Value to toggle
* @param {Boolean} Optional: Boolean to determine whether to add or remove
* @return {Array} Result
*/
_.mixin({'arrayToggle': function(arr, val, state) {
if ( _.indexOf(arr,val)==-1 || state)
return _.union(arr,[val]);
else
return _.without(arr,val);
}});