Skip to content

Instantly share code, notes, and snippets.

@rjack
Created January 28, 2011 11:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rjack/800132 to your computer and use it in GitHub Desktop.
Save rjack/800132 to your computer and use it in GitHub Desktop.
Test for stackoverflow question http://bit.ly/f3Tn0f. Runs in nodejs.
var uuid = require('node-uuid'), // npm install node-uuid
crypto = require('crypto');
var UUID_NUM = 1000000;
var uuid_table = {};
var methods = {
"sha1_take_first_20": {
descr: "Take first 20 characters of a SHA1 hex string",
fn: function (uuid)
{
var sha1 = crypto.createHash("sha1");
sha1.update(uuid);
return sha1.digest("hex").substring(0,20);
},
hashes: {},
collision_count: 0
}
}
var i, id;
console.log("Generating", UUID_NUM, "UUIDs...");
for (i = 0; i < UUID_NUM; i++) {
id = uuid();
if (uuid_table[id]) {
console.log("Ignoring duplicated ID");
i--;
} else {
uuid_table[id] = true;
}
}
console.log("Done");
var method, hash;
for (method in methods) {
console.log("Testing method", method, "...");
for (id in uuid_table) {
hash = methods[method].fn(id);
if (methods[method].hashes[hash]) {
methods[method].collision_count++;
//console.log("collision! hash", hash, ", uuid", id);
} else {
methods[method].hashes[hash] = true;
}
}
}
console.log("Results:");
for (method in methods) {
console.log(method, ":", methods[method].collision_count, "collisions");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment