Advertisement
rgruber

fastHash

Mar 29th, 2025
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.21 KB | Source Code | 0 0
  1. function fastHash(str, seed = 0) {
  2.     const p1 = 2654435761 >>> 0; // Prime 1
  3.     const p2 = 1597334677 >>> 0; // Prime 2
  4.     const p3 = 2246822519 >>> 0; // Prime 3
  5.     let h = seed + p1;
  6.  
  7.     let i = 0;
  8.     const len = str.length;
  9.  
  10.     // Process 4 bytes at a time
  11.     while (i + 4 <= len) {
  12.         let k = (str.charCodeAt(i) & 0xff) |
  13.                 ((str.charCodeAt(i + 1) & 0xff) << 8) |
  14.                 ((str.charCodeAt(i + 2) & 0xff) << 16) |
  15.                 ((str.charCodeAt(i + 3) & 0xff) << 24);
  16.        
  17.         k = Math.imul(k, p2);
  18.         h = Math.imul(h ^ (k >>> 16), p1);
  19.         h = Math.imul(h ^ k, p3);
  20.         i += 4;
  21.     }
  22.  
  23.     // Handle remaining bytes
  24.     while (i < len) {
  25.         h ^= (str.charCodeAt(i) & 0xff);
  26.         h = Math.imul(h, p1);
  27.         i++;
  28.     }
  29.  
  30.     // Finalization
  31.     h ^= h >>> 13;
  32.     h = Math.imul(h, p2);
  33.     h ^= h >>> 16;
  34.  
  35.     return h >>> 0; // Ensure unsigned 32-bit
  36. }
  37.  
  38. // Usage
  39. const text = "Hello World";
  40. console.log(fastHash(text)); // Outputs a number like 3894213542
  41.  
  42. // Test with multiple strings
  43. const tests = ["Hello World", "Test String", "Another One"];
  44. tests.forEach(str => {
  45.     console.log(`${str}: ${fastHash(str)}`);
  46. });
Tags: fastHash
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement