Last active
June 9, 2020 23:43
-
-
Save lcherone/d4895e4e82e2891ecab45ec9578fc488 to your computer and use it in GitHub Desktop.
FNV hash function, 32/64
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
/** | |
* 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