Skip to content

Instantly share code, notes, and snippets.

@mpuz
Created March 18, 2020 14:50
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 mpuz/e62ada1e73371432d00c566deefb0d2e to your computer and use it in GitHub Desktop.
Save mpuz/e62ada1e73371432d00c566deefb0d2e to your computer and use it in GitHub Desktop.
JavaScript implementation of hashcode
/**
* 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;
};
@mpuz
Copy link
Author

mpuz commented Mar 18, 2020

hashCode = s => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)

@mpuz
Copy link
Author

mpuz commented Mar 18, 2020

function hashCode(s) {
    for(var i = 0, h = 0; i < s.length; i++)
        h = Math.imul(31, h) + s.charCodeAt(i) | 0;
    return h;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment