LoDash.js Archives - Thoughts https://blog.jstassen.com/tag/lodash-js/ A place for collecting my miscellaneous thoughts. Thu, 17 Mar 2016 14:05:20 +0000 en-US hourly 1 https://wordpress.org/?v=7.0.7 92836340 LoDash.js / Underscore.js mixins https://blog.jstassen.com/2015/09/lodash-js-underscore-js-mixins/ https://blog.jstassen.com/2015/09/lodash-js-underscore-js-mixins/#respond Wed, 23 Sep 2015 21:44:01 +0000 http://blog.jstassen.com/?p=684 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 … Continue reading LoDash.js / Underscore.js mixins →

The post LoDash.js / Underscore.js mixins appeared first on Thoughts.

]]>
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);
}});

The post LoDash.js / Underscore.js mixins appeared first on Thoughts.

]]>
https://blog.jstassen.com/2015/09/lodash-js-underscore-js-mixins/feed/ 0 684