Created
November 7, 2010 10:39
-
-
Save rjungemann/666056 to your computer and use it in GitHub Desktop.
Playing with hashing algorithms
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
// use a hashing algorithm (in this case, SHA-1) to predictably assign | |
// a key to a particular slot. May be useful for sharding purposes. | |
// Based off of ideas found at: | |
// | |
// https://github.com/antirez/redis/blob/master/design-documents/REDIS-CLUSTER | |
var crypto = require('crypto'); | |
// digits -- number of digits to check | |
// slotSize -- number of slots to assign to | |
var Hasher = function(digits, slotSize) { | |
var maxDigitsSize = Math.pow(16, digits); | |
if(slotSize > maxDigitsSize) { | |
throw("slotSize must be < 16 ^ " + digits); | |
} | |
this.hash = function(key) { | |
var h = crypto.createHash('sha1').update(key).digest("hex"); | |
var significants = h.substring(h.length - digits); | |
var decimalSignificants = parseInt(significants, 16); | |
return Math.floor( | |
slotSize * (decimalSignificants / maxDigitsSize) | |
); | |
} | |
} | |
//var hasher = new Hasher(10, 1024); | |
// | |
// console.log(hasher.hash("h")); // => 423 | |
// console.log(hasher.hash("h")); // => 423 | |
// console.log(hasher.hash("hello, world!")); // => 667 | |
// console.log(hasher.hash("hello, world")); // => 456 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment