-
-
Save lwd-temp/d89a7fc7f33a995e59c17a767dd6a192 to your computer and use it in GitHub Desktop.
JavaScript Implementation of String.hashCode() .
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
/** | |
* Returns a hash code for a string. | |
* (Compatible to Java's String.hashCode()) | |
* | |
* The hash code for a string object is computed as | |
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] | |
* using number arithmetic, where s[i] is the i th character | |
* of the given string, n is the length of the string, | |
* and ^ indicates exponentiation. | |
* (The hash value of the empty string is zero.) | |
* | |
* @param {string} s a string | |
* @return {number} a hash code value for the given string. | |
*/ | |
hashCode = function(s) { | |
var h = 0, l = s.length, i = 0; | |
if ( l > 0 ) | |
while (i < l) | |
h = (h << 5) - h + s.charCodeAt(i++) | 0; | |
return h; | |
}; |
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
> hashCode('') | |
0 | |
> hashCode('Hello') | |
69609650 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment