Advertisement
rgruber

murmurhash3_32

Mar 29th, 2025
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function murmurhash3_32(key, seed = 0) {
  2.     const c1 = 0xcc9e2d51;
  3.     const c2 = 0x1b873593;
  4.     const r1 = 15;
  5.     const r2 = 13;
  6.     const m = 5;
  7.     const n = 0xe6546b64;
  8.  
  9.     let hash = seed;
  10.     let len = key.length;
  11.    
  12.     const getUint32 = (str, pos) => {
  13.         return (str.charCodeAt(pos) & 0xff) |
  14.                ((str.charCodeAt(pos + 1) & 0xff) << 8) |
  15.                ((str.charCodeAt(pos + 2) & 0xff) << 16) |
  16.                ((str.charCodeAt(pos + 3) & 0xff) << 24);
  17.     };
  18.  
  19.     let i = 0;
  20.     while (i + 4 <= len) {
  21.         let k = getUint32(key, i);
  22.         k = Math.imul(k, c1);
  23.         k = (k << r1) | (k >>> (32 - r1));
  24.         k = Math.imul(k, c2);
  25.        
  26.         hash ^= k;
  27.         hash = (hash << r2) | (hash >>> (32 - r2));
  28.         hash = Math.imul(hash, m) + n;
  29.         i += 4;
  30.     }
  31.  
  32.     let remaining = len % 4;
  33.     if (remaining > 0) {
  34.         let k = 0;
  35.         for (let j = 0; j < remaining; j++) {
  36.             k |= (key.charCodeAt(i + j) & 0xff) << (j * 8);
  37.         }
  38.         k = Math.imul(k, c1);
  39.         k = (k << r1) | (k >>> (32 - r1));
  40.         k = Math.imul(k, c2);
  41.         hash ^= k;
  42.     }
  43.  
  44.     hash ^= len;
  45.     hash ^= (hash >>> 16);
  46.     hash = Math.imul(hash, 0x85ebca6b);
  47.     hash ^= (hash >>> 13);
  48.     hash = Math.imul(hash, 0xc2b2ae35);
  49.     hash ^= (hash >>> 16);
  50.  
  51.     return hash >>> 0; // Ensure unsigned 32-bit
  52. }
  53.  
  54. // Usage
  55. const text = "Hello World";
  56. console.log(murmurhash3_32(text)); // Outputs a number like 2951470589
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement