Skip to content

Instantly share code, notes, and snippets.

@bitboxx
Created January 19, 2016 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitboxx/d4b73576f4a9c130b546 to your computer and use it in GitHub Desktop.
Save bitboxx/d4b73576f4a9c130b546 to your computer and use it in GitHub Desktop.
Javascript hashCode function
/**
* 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