Last active
August 29, 2015 14:03
-
-
Save omarduarte/2428e93c7577255337e3 to your computer and use it in GitHub Desktop.
This file contains 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
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 | |
*/ |
This file contains 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 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.