Skip to content

Instantly share code, notes, and snippets.

@ebeloded
Created May 22, 2023 07:16
Show Gist options
  • Save ebeloded/bf0b1ae06a410528464573369fa24e43 to your computer and use it in GitHub Desktop.
Save ebeloded/bf0b1ae06a410528464573369fa24e43 to your computer and use it in GitHub Desktop.
simpleHash
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