-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash-table.js
59 lines (51 loc) · 1.15 KB
/
hash-table.js
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class HashTable{
#size = 0;
#table = [];
#isPrime(n){
let result = [];
let d = 2;
while(d * d <= n){
if(n % d == 0){
result.push(d);
n = Math.floor(n / d);
}
else{
d ++;
}
}
if(n > 1){
result.push(n);
}
if(result.length > 1) return false;
else return true;
}
#nearestPrime(n){
if(n % 2 == 0){
n ++;
}
while(!this.#isPrime(n)){
n += 2;
}
return n;
}
#countHash(s){
let n = 7;
for(let c of s){
n = n * 31 + c.charCodeAt(0);
}
return Math.floor(this.#size * (n * ((Math.sqrt(5) - 1) / 2) % 1));
}
constructor(size){
this.#size = this.#nearestPrime(size);
this.#table = Array(this.#size).fill(undefined);
}
search(key){
return this.#table[this.#countHash(key)];
}
insert(key, value){
this.#table[this.#countHash(key)] = value;
}
remove(key){
this.#table[this.#countHash(key)] = undefined;
}
}