A common technique for hashing is to start with 0. Then you multiply the existing hash value by a prime number, and finally add the new element to it.
In this case:
((hash << 5) - hash)
is effectively "hash * 31". Apply the left shift operator, <<
, 5 times is like multiplying the number by 2, 5 times. Or, multiplying it by 2^5, which is 32. Then they subtract once, giving 31.
The hash & hash
is effectively a "do nothing" operation, performing a logical AND (&
) on a number with itself returns the same number, it doesn't "do anything", but it may be used to coerce the number and make sure it remains an integer. There's likely some JS machinations going on with the representation of the number and that's what the second line is for.
If this was just raw C, it would simply be hash = hash * 31 + char
.