forked from amazingandyyy/algor-in-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04-hash-table.js
78 lines (71 loc) · 2.02 KB
/
04-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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Big O Notation: O (1)
class HashTable {
constructor(size) {
this.bucket = Array(size);
this.numBucket = this.bucket.length;
}
hash(key) {
var total = key.split("").reduce((curr, next) => curr + next.charCodeAt(0), 0);
return total % this.numBucket;
}
insert(key, value) {
var index = this.hash(key);
if (!this.bucket[index])
this.bucket[index] = new HashNode(key, value);
else if (this.bucket[index].key === key) {
// update value if it's already exist
this.bucket[index].value = value;
}
else {
var currentNode = this.bucket[index];
while (currentNode.next) {
if (currentNode.next.key === key) {
// in order to check the last element in this while loop
currentNode.next.value = value;
return;
}
currentNode = currentNode.next;
}
currentNode.next = new HashNode(key, value);
}
}
get(key) {
var index = this.hash(key);
if (!this.bucket[index]) return null;
if (this.bucket[key] === key) return this.bucket[key];
else {
var currentNode = this.bucket[index];
while (currentNode) {
if (currentNode.key === key) return currentNode;
currentNode = currentNode.next;
}
return null;
}
}
retriveAll() {
var result = [];
for (var i=0 ; i < this.numBucket; i++){
var currentNode = this.bucket[i];
while(currentNode) {
result.push(currentNode);
currentNode = currentNode.next;
}
}
return result;
}
}
function HashNode(key, value, next) {
this.key = key;
this.value = value;
this.next = next || null;
}
var myHT = new HashTable(30);
myHT.insert('Andy', '[email protected]');
myHT.insert('Nady', '[email protected]');
myHT.insert('Bob', '[email protected]');
console.log('old', myHT);
myHT.insert('Andy', '[email protected]');
// console.log('new', myHT);
// console.log(myHT.get("Nayd")); // null
// console.log(myHT.get("Andy")); // '[email protected]'
console.log('retriveAll', myHT.retriveAll());