I'm trying to learn how to do some basic hashing in Javascript and I've come across the following algorithm:
var hash = 0;
for (i = 0; i < this.length; i++) {
char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash;
}
I don't really understand how it works and I was hoping you could help me out. In particular I don't understand (hash<<5)-hash and hash = hash & hash. Thank you for your replies.
Note: For anyone looking for the source, it's an implementation of Java’s String.hashCode(): http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method
hash = hash & hashstep looks superfluous. It may be there to keep the value in the integer range, I suppose.