Skip to content

Instantly share code, notes, and snippets.

@rubenreyes2000
Created February 2, 2024 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubenreyes2000/4896a735ec6013ae7820dd8b3c104bfb to your computer and use it in GitHub Desktop.
Save rubenreyes2000/4896a735ec6013ae7820dd8b3c104bfb to your computer and use it in GitHub Desktop.
Simple Hash function in JavaScript
/**
* A simple hashing function based on FNV-1a (Fowler-Noll-Vo) algorithm
* @param str the string to hash
* @returns the hash of the string
* @see https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
* Outputs a 128-bit hash (32 characters long)
*/
const hash = (str) => {
const FNV_PRIME = 0x01000193;
const h = [0x811c9dc5, 0x056892cd, 0x6b6b2d4f, 0x458e7388];
str += 't%V7t6Bu0^sN5zrjAZF*%eAVd49H0DhL';
for (let i = 0; i < str.length; i++) {
for (let j = 0; j < h.length; j++) {
if (j == 0) h[j] ^= str.charCodeAt(i);
else h[j] ^= h[j - 1];
h[j] *= FNV_PRIME;
}
}
return h.map(v => (v >>> 0).toString(16).padStart(8, '0')).join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment