Created
December 14, 2011 21:49
-
-
Save jaydson/1478713 to your computer and use it in GitHub Desktop.
Simple function to deal with big nesting objects
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
var use = function(package){ | |
var steps = package.split('/'), /* Nesting */ | |
pack = window[steps[0]]; /* Global reference */ | |
/* Remove first element */ | |
steps.shift() | |
/* Errors */ | |
if(steps.length < 1){ | |
throw "Hmm, why don't you provided a package? "; | |
} | |
if(!pack){ | |
throw "There's no " + steps[0] + " global Object in your app! "; | |
} | |
/* Object Recursive deep */ | |
function deep(steps){ | |
var s = steps; | |
if(pack[s[0]]){ | |
pack = pack[s[0]]; | |
s.shift(1); | |
deep(s); | |
} | |
} | |
/* There's a package? Call recursive function */ | |
if(package !== '' && package !== undefined && package !== null){ | |
deep(steps); | |
} | |
return pack; | |
}; | |
/* | |
How to use ? | |
Look at this literal object | |
*/ | |
var library = { | |
tools : { | |
foo : { | |
bar : { | |
baz : { | |
bin : function(){ | |
alert('library/tools/foo/bar/baz/foo') | |
} | |
} | |
} | |
} | |
} | |
}; | |
/* I know it's sucks... but, with this function you can do this: */ | |
var baz = use('library/tools/foo/bar/baz'); | |
baz.bin(); | |
/* Instead of using */ | |
library.tools.foo.bar.baz.bin(); | |
/* | |
It's useful ? | |
Is for nothing? | |
Well... I just thought about it and decided to create this snippet. | |
Enjoy, or not! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment