* Converts key string to hash number. * * @param {string} key * @return {number}
(key)
| 25 | * @return {number} |
| 26 | */ |
| 27 | hash(key) { |
| 28 | // For simplicity reasons we will just use character codes sum of all characters of the key |
| 29 | // to calculate the hash. |
| 30 | // |
| 31 | // But you may also use more sophisticated approaches like polynomial string hash to reduce the |
| 32 | // number of collisions: |
| 33 | // |
| 34 | // hash = charCodeAt(0) * PRIME^(n-1) + charCodeAt(1) * PRIME^(n-2) + ... + charCodeAt(n-1) |
| 35 | // |
| 36 | // where charCodeAt(i) is the i-th character code of the key, n is the length of the key and |
| 37 | // PRIME is just any prime number like 31. |
| 38 | const hash = Array.from(key).reduce( |
| 39 | (hashAccumulator, keySymbol) => (hashAccumulator + keySymbol.charCodeAt(0)), |
| 40 | 0, |
| 41 | ); |
| 42 | |
| 43 | // Reduce hash number so it would fit hash table size. |
| 44 | return hash % this.buckets.length; |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * @param {string} key |
no outgoing calls
no test coverage detected