Skip to content

Instantly share code, notes, and snippets.

@lcherone

lcherone/fnv.js

Last active Jun 9, 2020
Embed
What would you like to do?
FNV hash function, 32/64
/**
* FNV hash
* - 32 bit FNV-1a hash
* - 64 bit FNV-1a hash
* @link http://isthe.com/chongo/tech/comp/fnv/
*
* Usage:
* fnv.hash('Hello World', 32) // 3012568359
* fnv.hash('Hello World', 64) // 3599595964
*/
const fnv = (function () {
const primes = {
32: 0x811c9dc5,
64: 0xcbf29ce484222325,
}
return {
hash(input = '', length = 32) {
input = input.toString()
if (!Object.keys(primes).map(i => Number(i)).includes(length))
throw Error('Length not supported')
let hval = primes[length] || 32
for (let i = 0; i < input.length; ++i) {
hval ^= input.charCodeAt(i)
hval += length === 32 ?
(hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24) :
(hval << 1) + (hval << 4) + (hval << 5) + (hval << 7) + (hval << 40)
}
return hval >>> 0
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment