MCPcopy Index your code
hub / github.com/trekhleb/javascript-algorithms / hash

Method hash

src/data-structures/hash-table/HashTable.js:27–45  ·  view source on GitHub ↗

* Converts key string to hash number. * * @param {string} key * @return {number}

(key)

Source from the content-addressed store, hash-verified

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

Callers 4

setMethod · 0.95
deleteMethod · 0.95
getMethod · 0.95
HashTable.test.jsFile · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected