Last active
February 5, 2022 01:24
-
-
Save netgusto/1dcb3fc607c1612d5a98324216d4564d to your computer and use it in GitHub Desktop.
Polynomial Hash for node.js
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 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