Skip to content

Instantly share code, notes, and snippets.

@hyamamoto
Created September 30, 2016 07:19
Show Gist options
  • Save hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0 to your computer and use it in GitHub Desktop.
Save hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0 to your computer and use it in GitHub Desktop.
JavaScript Implementation of String.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;
};
> hashCode('')
0
> hashCode('Hello')
69609650
@jlevy
Copy link

jlevy commented Feb 15, 2024

Just FYI, another take on the same problem here, with both an old Java-style hash and with a version of @bryc's excellent, more modern cyrb53 hash:
https://gist.github.com/jlevy/c246006675becc446360a798e2b2d781

@DL259
Copy link

DL259 commented May 16, 2024

What about a hashCode of an object in JS? Maybe that can only happen in C/C++ land.

You can use JSON.stringify(object) to turn it into a string first, then encode, then when you decode, turn it back into an object with JSON.parse()

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