Created
April 12, 2021 12:49
-
-
Save yuler/00d7d959d2fa90351d961a744b1b6e4c to your computer and use it in GitHub Desktop.
Javascript implementation of Java’s String.hashCode() method
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
| /** | |
| * Javascript implementation of Java’s String.hashCode() method | |
| * refs: https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method | |
| * refs: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#hashCode-- | |
| * | |
| * Returns a hash code for a string. | |
| * @param str string | |
| * @return number | |
| */ | |
| function hash(str) { | |
| let hash = 0 | |
| for (let i = 0; i < str.length; i++) { | |
| hash = (hash << 5) - hash + str.charCodeAt(i) | |
| hash |= 0 // Convert to 32bit integer | |
| } | |
| return hash | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment