Created
May 22, 2023 07:16
-
-
Save ebeloded/bf0b1ae06a410528464573369fa24e43 to your computer and use it in GitHub Desktop.
simpleHash
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
const getN2 = | |
(maxN: number) => | |
(s: string): number => { | |
let hash = 0 | |
for (let i = 0; i < s.length; i++) { | |
// Compute a hash by rotating the previous hash and XORing with the current character | |
hash = (hash << 5) ^ (hash >> 27) ^ s.charCodeAt(i) | |
} | |
// Apply modulo operation to keep hash within range, and take absolute in case it's negative | |
return Math.abs(hash % maxN) | |
} | |
const getN3 = | |
(maxN: number) => | |
(s: string): number => { | |
let hash = 0 | |
const prime = 31 // Use a prime number for hashing | |
for (let i = 0; i < s.length; i++) { | |
// Shift hash by prime and add character code | |
hash = hash * prime + s.charCodeAt(i) | |
} | |
// Apply modulo operation to keep hash within range | |
return Math.abs(hash % maxN) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment