Created
January 19, 2016 09:43
-
-
Save bitboxx/d4b73576f4a9c130b546 to your computer and use it in GitHub Desktop.
Javascript hashCode function
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 hashCode function | |
* This function is a modified version of 'Javascript implementation of Java’s String.hashCode() method' | |
* | |
* Modifications: | |
* - Added comments | |
* - Added string length caching | |
* - Regular function instead of String.prototype | |
* - Variable char (reserved word) is renamed to tmpChar. | |
* | |
* The original code can be found on this page: | |
* http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/ | |
*/ | |
function hashCode(string) { | |
var hash = 0; | |
var tmpChar; | |
var index; | |
var stringLength = string.length | |
// if the string es empty, then return immediately | |
if (stringLength === 0) { | |
return hash; | |
} | |
// loop the string | |
for (index = 0; index < stringLength; index++) { | |
// get character code at the index location | |
tmpChar = string.charCodeAt(index); | |
// left shift etc. | |
hash = ((hash << 5) - hash) + tmpChar; | |
// bitwise AND etc. | |
hash = hash & hash; // Convert to 32bit integer | |
} | |
return hash; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment