Created
July 2, 2012 01:59
-
-
Save ityonemo/3030494 to your computer and use it in GitHub Desktop.
"Implementing" Hashes in Javascript
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
//Hash.js -- a cute little wrapper that is really great for turning data-only objects into something that | |
//javascript explictly calls a "Hash". Useful for cosmetically improving data structure representations | |
//in your favorite console. also great for making Javascript look like some of the more friendly scripting | |
//languages like Ruby. Possibly useless for anything else, and may make your code easier to read at the | |
//expense of speed and/or memory. | |
Hash = function(object) | |
{ | |
if (object && (typeof object == 'object')) //do an initial type check to see if this can be hashified. | |
{ //if not, then you should return an empty hash {}. | |
if (object instanceof Array) //special case, we have passed an array. | |
{ | |
var a = new Array(); //create a new array that is going to go into our hash. | |
for (var i = 0; i < object.length; i++) //iterate over the passed array. | |
if (typeof object[i] != 'object' || object[i] == null) | |
a.push(object[i]); //if it's a boring member, just push it onto the array | |
else | |
a.push(new Hash(object[i])); //if it's an object member, call hash again. | |
return a; //yes! you can effectively bypass the "new" by returning a value | |
} //this overrides the Hash object creation and keeps Arrays as is. | |
else | |
for (var o in object) //iterate over the objects in our source | |
{ | |
if ((typeof object[o] != 'object') || object[o] == null) | |
this[o] = object[o] //if it's boring, just add it to the hash. | |
else | |
this[o] = new Hash(object[o]); //iterate hash-ification! | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment