Skip to content

Instantly share code, notes, and snippets.

@r37r0m0d3l
Created January 9, 2013 13:36
Show Gist options
  • Save r37r0m0d3l/4493158 to your computer and use it in GitHub Desktop.
Save r37r0m0d3l/4493158 to your computer and use it in GitHub Desktop.
Works same as Java’s String.hashCode()
/**
* String hash code
* @param {String} str
* @return {int}
*/
function hashCode(str) {
for (var result = 0, i = 0; i < str.length; i++) {
result = (result << 5) - result + str.charCodeAt(i);
result &= result;
}
return result;
}
// Compressed
function(e){for(var r=0,i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r&=r;return r};
// Usage
console.log(hashCode("Secret message"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment