Created
December 30, 2011 16:38
-
-
Save fantactuka/1540550 to your computer and use it in GitHub Desktop.
Creates hash code from string, ported from #C
This file contains hidden or 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
| // 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); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To properly match the output of the 32-bit C# version, the return line must be changed:
The
| 0is necessary to handle addition overflow issues. Without it, a result can be -2905053384 which uses 33 bits, however it would be 1389913912 in a realinttype 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. 🙄