Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function fastHash(str, seed = 0) {
- const p1 = 2654435761 >>> 0; // Prime 1
- const p2 = 1597334677 >>> 0; // Prime 2
- const p3 = 2246822519 >>> 0; // Prime 3
- let h = seed + p1;
- let i = 0;
- const len = str.length;
- // Process 4 bytes at a time
- while (i + 4 <= len) {
- let k = (str.charCodeAt(i) & 0xff) |
- ((str.charCodeAt(i + 1) & 0xff) << 8) |
- ((str.charCodeAt(i + 2) & 0xff) << 16) |
- ((str.charCodeAt(i + 3) & 0xff) << 24);
- k = Math.imul(k, p2);
- h = Math.imul(h ^ (k >>> 16), p1);
- h = Math.imul(h ^ k, p3);
- i += 4;
- }
- // Handle remaining bytes
- while (i < len) {
- h ^= (str.charCodeAt(i) & 0xff);
- h = Math.imul(h, p1);
- i++;
- }
- // Finalization
- h ^= h >>> 13;
- h = Math.imul(h, p2);
- h ^= h >>> 16;
- return h >>> 0; // Ensure unsigned 32-bit
- }
- // Usage
- const text = "Hello World";
- console.log(fastHash(text)); // Outputs a number like 3894213542
- // Test with multiple strings
- const tests = ["Hello World", "Test String", "Another One"];
- tests.forEach(str => {
- console.log(`${str}: ${fastHash(str)}`);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement