Skip to content

Instantly share code, notes, and snippets.

@elycruz
Last active August 29, 2015 13:56
Show Gist options
  • Save elycruz/9059930 to your computer and use it in GitHub Desktop.
Save elycruz/9059930 to your computer and use it in GitHub Desktop.
/**
* Created by edelacruz on 2/17/14.
*/
(function (context) {
/**
* Takes a namespace string and fetches that location out from
* an object/Map. If the namespace doesn't exists it is created then
* returned.
* Example: _namespace('hello.world.how.are.you.doing', obj) will
* create/fetch within `obj`:
* hello: { world: { how: { are: { you: { doing: {} } } } } }
* @param ns_string {String} the namespace you wish to fetch
* @param objToSearch {Object} object to search for namespace on
* @param valueToSet {Object} optional, a value to set on the key
* (last key if key string (a.b.c.d = value))
* @param createEs6 {Boolean} optional, default `false` set undefined
* parts of `ns_string` in search with an es6 collection (only maps allowed at the
* moment as maps are the only es6 realistic use cases for _namespacing).
* @returns {Object}
*/
context._namespace = function (ns_string, objToSearch, valueToSet, createEs6) {
createEs6 = createEs6 || false;
var parts = ns_string.split('.'),
parent = objToSearch,
shouldSetValue = classOfIs(valueToSet, 'Undefined')
? false : true;
i;
for (i = 0; i < parts.length; i += 1) {
// Traverse es6 collections (only maps currently supported)
if (classOfIs(parent, 'Map')) {
// If part not set set it
if (!parent.has(parts[i])) {
var newObj = createEs6 && !shouldSetValue ? new Map() :
(shouldSetValue ? valueToSet : {});
parent.set(parts[i], newObj);
parent = newObj;
}
// If part is set
else {
// Set value if necessary
if (shouldSetValue) {
parent.set(parts[i], valueToSet);
}
parent = parent.get(parts[i]);
}
}
// Assume parent is an {Object}
else {
if (classOfIs(parent[parts[i]], 'Undefined')) {
parent[parts[i]] = {};
}
if (i === parts.length - 1 && shouldSetValue) {
parent[parts[i]] = valueToSet;
}
parent = parent[parts[i]];
}
};
};
})(typeof window !== "undefined" ? window : global);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment