-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.js
113 lines (93 loc) · 3.16 KB
/
HashTable.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class HashTable {
constructor(initialCapacity = 8) {
this.size = 0;
this.capacity = initialCapacity;
this.buckets = new Array(initialCapacity);
this.threshold = Math.floor(initialCapacity * 0.75);
}
put(key, value) {
const bucketIndex = this._getBucketIndex(key);
if (!this.buckets[bucketIndex]) {
this.buckets[bucketIndex] = [];
} else {
for (let i = 0; i < bucket.length; i++) {
if (this.buckets[bucketIndex][i][0] === key) {
this.buckets[bucketIndex][i][1] = value;
return;
}
}
}
this.buckets[bucketIndex].push([key, value]);
this.size++;
if (this.size >= this.threshold) {
this._resize(this.capacity * 2);
}
}
get(key) {
const bucketIndex = this._getBucketIndex(key);
if (this.buckets[bucketIndex]) {
for (let i = 0; i < this.buckets[bucketIndex].length; i++) {
if (this.buckets[bucketIndex][i][0] === key) {
return this.buckets[bucketIndex][i][1];
}
}
}
return null;
}
containsKey(key) {
const bucketIndex = this._getBucketIndex(key);
if (this.buckets[bucketIndex]) {
for (let i = 0; i < this.buckets[bucketIndex].length; i++) {
if (this.buckets[bucketIndex][i][0] === key) {
return true;
}
}
}
return false;
}
remove(key) {
const hash = this._hash(key);
const bucketIndex = hash % this.buckets.length;
if (this.buckets[bucketIndex]) {
for (let i = 0; i < this.buckets[bucketIndex].length; i++) {
if (this.buckets[bucketIndex][i][0] === key) {
this.buckets[bucketIndex].splice(i, 1);
this.size--;
if (this.capacity > 8 && this.size < Math.floor(this.capacity * 0.25)) {
this._resize(Math.floor(this.capacity / 2));
}
return true;
}
}
}
return false;
}
_hash(key) {
let hashCode = 0;
for (let i = 0; i < key.length; i++) {
hashCode = ((hashCode << 5) - hashCode) + key.charCodeAt(i);
hashCode |= 0;
}
return hashCode;
}
_getBucketIndex(key) {
const hashCode = this._hash(key);
return hashCode % this.capacity;
}
_resize(newCapacity) {
const oldBuckets = this.buckets;
this.capacity = newCapacity;
this.buckets = new Array(newCapacity);
this.threshold = Math.floor(newCapacity * 0.75);
this.size = 0;
for (let i = 0; i < oldBuckets.length; i++) {
if (oldBuckets[i]) {
for (let j = 0; j < oldBuckets[i].length; j++) {
const [key, value] = oldBuckets[i][j];
this.put(key, value);
}
}
}
}
}
module.exports = HashTable;