Skip to content

Instantly share code, notes, and snippets.

@yuler
Created April 12, 2021 12:49
Show Gist options
  • Select an option

  • Save yuler/00d7d959d2fa90351d961a744b1b6e4c to your computer and use it in GitHub Desktop.

Select an option

Save yuler/00d7d959d2fa90351d961a744b1b6e4c to your computer and use it in GitHub Desktop.
Javascript implementation of Java’s String.hashCode() method
/**
* 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