-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHashTable.js
More file actions
79 lines (77 loc) · 1.86 KB
/
Copy pathHashTable.js
File metadata and controls
79 lines (77 loc) · 1.86 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class HashTable {
constructor() {
this.buckets = new Array(100);
}
hash(key) {
const str = String(key);
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = (hash * 33 + str.charCodeAt(i)) % this.buckets.length;
}
return hash;
}
set(key, value) {
const index = this.hash(key);
if (!this.buckets[index]) {
this.buckets[index] = [];
}
// check if the key already exists in the bucket
for (let i = 0; i < this.buckets[index].length; i++) {
if (this.buckets[index][i][0] === key) {
this.buckets[index][i][1] = value;
return;
}
}
// if key doesn't exist, add a new key-value pair
this.buckets[index].push([key, value]);
}
get(key) {
const index = this.hash(key);
if (!this.buckets[index]) {
return null;
}
for (let i = 0; i < this.buckets[index].length; i++) {
if (this.buckets[index][i][0] === key) {
return this.buckets[index][i][1];
}
}
return null;
}
delete(key) {
const index = this.hash(key);
if (!this.buckets[index]) {
return false;
}
for (let i = 0; i < this.buckets[index].length; i++) {
if (this.buckets[index][i][0] === key) {
this.buckets[index].splice(i, 1);
return true;
}
}
return false;
}
has(key) {
const index = this.hash(key);
if (!this.buckets[index]) {
return false;
}
for (let i = 0; i < this.buckets[index].length; i++) {
if (this.buckets[index][i][0] === key) {
return true;
}
}
return false;
}
getValue() {
const values = [];
for (let i = 0; i < this.buckets.length; i++) {
if (this.buckets[i]) {
for (let j = 0; j < this.buckets[i].length; j++) {
values.push(this.buckets[i][j][1]);
}
}
}
return values;
}
}
module.exports = HashTable;