Skip to content

Instantly share code, notes, and snippets.

@icorbrey
Created June 21, 2022 14:51
Show Gist options
  • Save icorbrey/1e1d912ac0741121a7413be0b3914622 to your computer and use it in GitHub Desktop.
Save icorbrey/1e1d912ac0741121a7413be0b3914622 to your computer and use it in GitHub Desktop.
/**
* Generates a hash code from the given string using the `cyrb53` hashing
* algorithm.
*
* @param {string} str
* @param {number=} seed
*/
export const hashCode = (str, seed = 0) => {
let h1 = 0xdeadbeef ^ seed;
let h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 0x9e3779b1);
h2 = Math.imul(h2 ^ ch, 0x5f356495);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 0x85ebca6b) ^ Math.imul(h2 ^ (h2 >>> 13), 0xc2b2ae35);
h2 = Math.imul(h2 ^ (h2 >>> 16), 0x85ebca6b) ^ Math.imul(h1 ^ (h1 >>> 13), 0xc2b2ae35);
return 0x100000000 * (0x1fffff & h2) + (h1 >>> 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment