Skip to content

Instantly share code, notes, and snippets.

@ciaranj
Created July 27, 2011 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ciaranj/1110433 to your computer and use it in GitHub Desktop.
Save ciaranj/1110433 to your computer and use it in GitHub Desktop.
function rehash (values) {
var hash = {}
, len
, i=0;
if (!Array.isArray(values)) return hash;
len= values.length
if( len % 2 == 1) return []; //mis-matched array ?
while( i < len) { // for(i =0 ;i < len; ) {
hash[values[i++]]= values[i++];
}
return hash;
}
function rehashB (values) {
var hash = {}
, isKey = true
, key;
if (!Array.isArray(values)) return hash;
values.forEach(function(value) {
if (isKey) {
key = value;
hash[key] = null;
} else {
hash[key] = value;
}
isKey = !isKey;
});
return hash;
}
function rehashC (xs) {
return xs.reduce(function (acc, x, i) {
if (i % 2 == 0) acc[x] = xs[i+1]
return acc;
}, {});
}
for(j=0;j< 10000;j++ ) {
rehashB(["a", "b", "c","d"])
rehash(["a", "b", "c","d"])
rehashC(["a", "b", "c","d"])
}
console.log( rehash(["a", "b", "c","d"]) )
console.log( rehashB(["a", "b", "c","d"]) )
console.log( rehashC(["a", "b", "c","d"]) )
var j= 0
, then
, now;
then= new Date();
for(j=0;j< 100000;j++ ) {
rehash(["a", "b", "c","d"])
}
now= new Date();
console.log( "ciaranj - " + (now.getTime() - then.getTime()) + "ms" );
then= new Date();
for(j=0;j< 100000;j++ ) {
rehashB(["a", "b", "c","d"])
}
now= new Date();
console.log( "Original - "+ (now.getTime() - then.getTime()) + "ms" );
then= new Date();
for(j=0;j< 100000;j++ ) {
rehashC(["a", "b", "c","d"])
}
now= new Date();
console.log( "Substack - " + (now.getTime() - then.getTime()) + "ms" );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment