Skip to content

Instantly share code, notes, and snippets.

@netgusto
Last active February 5, 2022 01:24
Show Gist options
  • Save netgusto/1dcb3fc607c1612d5a98324216d4564d to your computer and use it in GitHub Desktop.
Save netgusto/1dcb3fc607c1612d5a98324216d4564d to your computer and use it in GitHub Desktop.
Polynomial Hash for node.js
const PRIME_BASE = 257;
const PRIME_MOD = 1000000007;
function polynomialHash(s) {
let hash = 0;
for (let i = 0; i < s.length; i++) {
hash = hash * PRIME_BASE + s.charCodeAt(i);
hash %= PRIME_MOD; //don't overflow
}
return hash;
}
console.log("polynomialHash(Paris)", polynomialHash("Paris"));
console.log("polynomialHash(Auckland)", polynomialHash("Auckland"));
console.log("polynomialHash(Peter)", polynomialHash("Peter"));
console.log("polynomialHash(Dover)", polynomialHash("Dover"));
// Outputs
// polynomialHash(Paris) 651721837
// polynomialHash(Auckland) 56642560
// polynomialHash(Peter) 719751278
// polynomialHash(Dover) 539984858
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment