Skip to content

Instantly share code, notes, and snippets.

@fantactuka
Created December 30, 2011 16:38
Show Gist options
  • Save fantactuka/1540550 to your computer and use it in GitHub Desktop.
Save fantactuka/1540550 to your computer and use it in GitHub Desktop.
Creates hash code from string, ported from #C
// Borrowed from http://stackoverflow.com/questions/5293174/creating-a-unique-id-from-an-array-of-strings-in-javascript
function getHashCode(str) {
var h1 = (5381 << 16) + 5381, h2 = h1, index = 0;
while (index < str.length) {
h1 = ((h1 << 5) + h1 + (h1 >> 27)) ^ str.charCodeAt(index);
if (index == str.length - 1) {
break;
}
h2 = ((h2 << 5) + h2 + (h2 >> 27)) ^ str.charCodeAt(index + 1);
index += 2;
}
return h1 + (h2 * 1566083941);
}
@bryc
Copy link

bryc commented Jan 12, 2019

To properly match the output of the 32-bit C# version, the return line must be changed:

return h1 + Math.imul(h2, 1566083941) | 0;

The | 0 is necessary to handle addition overflow issues. Without it, a result can be -2905053384 which uses 33 bits, however it would be 1389913912 in a real int type in C# due to overflow. This method also retains 'real' signed integer outputs, just as it should.

Keep in mind this version does not actually match the original GetHashCode output because the original was implemented with UTF-16 strings in mind--two characters per int. But this version is more "sane" or traditional. Also, it's not even that good of a hash function. 🙄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment