Skip to content

Instantly share code, notes, and snippets.

@niyazpk
Created December 11, 2012 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niyazpk/4257608 to your computer and use it in GitHub Desktop.
Save niyazpk/4257608 to your computer and use it in GitHub Desktop.
A murmur hash implemetation
crypto = (function (){
/**
* JS Implementation of MurmurHash2
*
* @see http://github.com/garycourt/murmurhash-js
*
* @param {string} str ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function murmurhash2_32_gc(str, seed) {
var
l = str.length,
h = (seed || 0x9747b28c) ^ l,
i = 0,
k,
a = 0xff,
b = 0xffff,
c = 0x5bd1e995;
while (l >= 4) {
k =
((str.charCodeAt(i) & a)) |
((str.charCodeAt(++i) & a) << 8) |
((str.charCodeAt(++i) & a) << 16) |
((str.charCodeAt(++i) & a) << 24);
k = (((k & b) * c) + ((((k >>> 16) * c) & b) << 16));
k ^= k >>> 24;
k = (((k & b) * c) + ((((k >>> 16) * c) & b) << 16));
h = (((h & b) * c) + ((((h >>> 16) * c) & b) << 16)) ^ k;
l -= 4;
++i;
}
switch (l) {
case 3: h ^= (str.charCodeAt(i + 2) & a) << 16;
case 2: h ^= (str.charCodeAt(i + 1) & a) << 8;
case 1: h ^= (str.charCodeAt(i) & a);
h = (((h & b) * c) + ((((h >>> 16) * c) & b) << 16));
}
h ^= h >>> 13;
h = (((h & b) * c) + ((((h >>> 16) * c) & b) << 16));
h ^= h >>> 15;
return h >>> 0;
}
return {
hash : murmurhash2_32_gc
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment