0

Here is the hashcode (written in javascript), source: https://github.com/m3talstorm/hashcode/blob/master/lib/hashcode.js:

const hash = (string) => {
    let hash = 0
    string = string.toString()
    for(let i = 0; i < string.length; i++) {
        hash = (((hash << 5) - hash) + string.charCodeAt(i)) & 0xFFFFFFFF
    }
    return hash
}

I don't understand the for loop.

1) Why is the developer shifting the hash variable 5 bits to the left and subtracting the hash value from the result?

2) Why is the developer using "&0xFFFFFFFF"? Doesn't any number ANDed with that just give the number itself?

I have seen it in two more examples, so I am assuming that this is a decently popular hashcode implementation. If so I'd like to learn it.

ThePumpkinMaster
  • 2,181
  • 5
  • 22
  • 31
  • 1
    “Doesn't any number ANDed with that just give the number itself?” If it’s a 32-bit integer, yes, but JavaScript numbers aren’t always that. `0xFFFFFFFF + 5` won’t overflow, for example, and so you would have to mask it again to get a 32-bit hash. – Ry- Apr 02 '17 at 02:16
  • Oh so because the number keeps shifting to the left, it could end up being longer than 32 bits. So the AND is there to keep the number at 32 bits? – ThePumpkinMaster Apr 02 '17 at 02:17
  • Kind of; the addition would be the part to make it longer than 32 bits, because `<<` truncates to 32 bits already in JavaScript. As for the hash itself… `(hash << 5) - hash` was probably intended to be a way to write `hash * 31` without multiplication to match Java’s: https://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier – Ry- Apr 02 '17 at 02:21

0 Answers0