Created
February 2, 2024 02:02
-
-
Save rubenreyes2000/4896a735ec6013ae7820dd8b3c104bfb to your computer and use it in GitHub Desktop.
Simple Hash function in JavaScript
This file contains 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
/** | |
* 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