1/**
2 * Calculate a 32 bit FNV-1a hash
3 * Found here: https://gist.github.com/vaiorabbit/5657561
4 * Ref.: http://isthe.com/chongo/tech/comp/fnv/
5 *
6 * @param {string} str the input value
7 * @param {boolean} [asString=false] set to true to return the hash value as
8 * 8-digit hex string instead of an integer
9 * @param {integer} [seed] optionally pass the hash of the previous chunk
10 * @returns {integer | string}
11 */
12function hashFnv32a(str, asString, seed) {
13 /*jshint bitwise:false */
14 var i, l,
15 hval = (seed === undefined) ? 0x811c9dc5 : seed;
16
17 for (i = 0, l = str.length; i < l; i++) {
18 hval ^= str.charCodeAt(i);
19 hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
20 }
21 if( asString ){
22 // Convert to 8 digit hex string
23 return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
24 }
25 return hval >>> 0;
26}
1function hashFnv32a(str, asString, seed) {
2 /*jshint bitwise:false */
3 var i, l,
4 hval = (seed === undefined) ? 0x811c9dc5 : seed;
5
6 for (i = 0, l = str.length; i < l; i++) {
7 hval ^= str.charCodeAt(i);
8 hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
9 }
10 if( asString ){
11 // Convert to 8 digit hex string
12 return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
13 }
14 return hval >>> 0;
15}
1function hashCode(str) {
2 return str.split('').reduce((prevHash, currVal) =>
3 (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
4}
5
6// Test
7console.log("hashCode(\"Hello!\"): ", hashCode('Hello!'));