-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash.js
More file actions
36 lines (27 loc) · 759 Bytes
/
hash.js
File metadata and controls
36 lines (27 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function hash(key, arrayLen) {
let total = 0;
for (let char of key) {
const value = char.charCodeAt(0) - 96;
total = (total + value) % arrayLen;
}
return total;
}
console.log(hash('orange', 10));
console.log(hash('blue', 10));
console.log(hash('cyan', 10));
console.log(hash('purple', 10));
console.log(hash('maroon', 10));
// improved
function hashFunction(key, arrayLen) {
let total = 0;
const weirdPrime = 31;
for (let i = 0; i < Math.min(key.length, 100); i++) {
const value = key[i].charCodeAt(0) - 96;
total = (total * weirdPrime + value) % arrayLen;
}
return total;
}
console.log(hashFunction('hello', 13));
console.log(hashFunction('goodbye', 13));
console.log(hashFunction('hi', 13));
console.log(hashFunction('cyan', 13));