Created
November 26, 2015 16:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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