Implementing Java's String.hashCode in JavaScript

Implementing Java's String.hashCode in JavaScript

I recently needed a simple way to keep track of if I had seen a particular string before. A naive way to approach this would have been simply to keep an array of all strings I had seen in an array and then do a ".includes(string)" on it. This wastes a lot of memory and takes a while to check.

This sounded like a great time to use a hash. Something like MD5 or SHA would be overkill. I didn't need it to be secure, just unique. In Java, each string has the method hashCode() on the object. It returns a 32 bit integer that is relatively guaranteed to be unique for any given string. JavaScript has no similar comparable utility. I looked up the implementation of the Java version and was surprised at how simple it was.

s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1]

Here's the implementation of an equivalent function in JS:

function hashString(str){
	let hash = 0;
	for (let i = 0; i < str.length; i++) {
		hash += Math.pow(str.charCodeAt(i) * 31, str.length - i);
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
}