forked from aneagoie/ztm-master-the-coding-interview-ds-algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashTableImplementation.js
60 lines (45 loc) · 1.23 KB
/
hashTableImplementation.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
class HashTable {
constructor(size) {
this.data = new Array(size);
}
// O(1)
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
// O(1)
set(key, value) {
let address = this._hash(key);
if (!this.data[address]) {
this.data[address] = [];
}
this.data[address].push([key, value]);
}
get(key) {
let address = this._hash(key);
const currentBucket = this.data[address];
if (currentBucket.length) {
for (let i = 0; i < currentBucket.length; i++) {
if (currentBucket[i][0] === key) {
return currentBucket[i][1];
}
}
}
return undefined;
}
keys() {
const keysArray = [];
const flatData = this.data.flat();
flatData.forEach(entry => keysArray.push(entry[0]));
return keysArray;
}
}
const myHashTable = new HashTable(50);
myHashTable.set("grapes", 10000);
myHashTable.set("apples", 54);
myHashTable.set("oranges", 2);
myHashTable.get("grapes");
console.log(myHashTable.keys());