Skip to content

Instantly share code, notes, and snippets.

@leandro
Created November 26, 2015 16:48
Show Gist options
  • Save leandro/1869f65a6868c9bea53c to your computer and use it in GitHub Desktop.
Save leandro/1869f65a6868c9bea53c to your computer and use it in GitHub Desktop.
Simple port of Ruby 2.3' Hash#dig into Javascript's Underscore lib
(function() {
'use strict';
_.mixin({
// Similar to `_.dig` but uses `window` as the starting point object.
import: function(namespace, initialValue) {
return _.dig(window, namespace, true, initialValue);
},
// Fetch or create the nested objects referenced in @namespace@ (String or Array)
// using the @baseObject@ as the starting point object. If the last reference
// in the namespace doesn't exist it'll create it and assign @_initialValue@ or {}
// as the initial value. If @_create@ is false it'll just try to navigate through
// the objects and return undefined if not found. If it's true it'll create the
// objects while navigating through them, if they don't exist.
dig: function(baseObject, namespace, _createObjects, _initialValue) {
var createObjects = _.isUndefined(_createObjects) ? false : !!_createObjects;
var initialValue = _.isUndefined(_initialValue) ? null : _initialValue;
var names = _.isArray(namespace) ? namespace : namespace.split('.');
var size = names.length;
_.find(names, function(name, index) {
if (createObjects && _.isUndefined(baseObject[name])) {
baseObject[name] = initialValue !== null && index === size - 1 ? initialValue : {};
}
baseObject = baseObject[name];
if (_.isUndefined(baseObject)) { return true; }
});
return baseObject;
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment