Skip to content

Instantly share code, notes, and snippets.

@omarduarte
Last active August 29, 2015 14:03
Show Gist options
  • Save omarduarte/2428e93c7577255337e3 to your computer and use it in GitHub Desktop.
Save omarduarte/2428e93c7577255337e3 to your computer and use it in GitHub Desktop.
Finish the namespace function so that it sets or gets the value at the path
specified. The first argument should be the root object that the path belongs to.
The 2nd argument is the path itself and the 3rd optional argument is the value
to set at the path.
If a value is provided then the path will be set to that value. Any objects not
present within the path will be created automatically in order for the path to
be successfully set.
/* CODE
* stuff = {}
* namespace(stuff, 'moreStuff.name', 'the stuff')
*
* results in {moreStuff: {name: 'the stuff'}}
*/
If no value is provided the the function will return the value at the path given.
If the path is not valid/present then undefined will be returned.
/* CODE
* namespace(stuff, 'moreStuff.name') # returns 'the stuff'
* namesace(stuff, 'otherStuff.id') # returns undefined
*/
function namespace(root, path, value){
var parts = path.split(".");
function setValue(objScroller, parts, value) {
var i;
for (i = 0; i < parts.length - 1 ; i++) {
if (!objScroller.hasOwnProperty(parts[i])) {
objScroller[parts[i]] = {};
}
objScroller = objScroller[parts[i]];
}
objScroller[parts.pop()] = value;
}
function getValue(objScroller,parts) {
var i;
for (i = 0; i < parts.length - 1 ; i++) {
if (!objScroller.hasOwnProperty(parts[i])) {
return undefined;
}
objScroller = objScroller[parts[i]];
}
return objScroller[parts.pop()];
}
return (value) ? setValue(root,parts,value) : getValue(root,parts);
}
@omarduarte
Copy link
Author

Coincidentally, I was just reading Nickolas Zackas' "Maintanable Javascript" where he was talking about the namespace function for your One Global Object. That served as inspiration for most of this kata.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment