-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhashTable.js
76 lines (68 loc) · 1.95 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
function HashTable(size) {
this.buckets = Array(size);
this.numBuckets = this.buckets.length;
}
function HashNode(key, value, next) {
this.key = key;
this.value = value;
this.next = next || null;
}
HashTable.prototype.hash = function(key) {
let total = 0;
for (let i = 0; i < key.length; i++) {
total += key.charCodeAt(i);
}
let bucket = total % this.numBuckets;
return bucket;
}
HashTable.prototype.insert = function(key, value) {
let index = this.hash(key);
if (!this.buckets[index]) this.buckets[index] = new HashNode(key, value);
else if (this.buckets[index].key === key) {
this.buckets[index].value = value;
}
else {
let currentNode = this.buckets[index];
while (currentNode.next) {
if (currentNode.next.key === key) {
currentNode.next.value = value;
return;
}
currentNode = currentNode.next;
}
currentNode.next = new HashNode(key, value);
}
}
HashTable.prototype.get = function(key) {
let index = this.hash(key);
if (!this.buckets[index]) return null;
else {
let currentNode = this.buckets[index];
while (currentNode) {
if (currentNode.key === key) return currentNode.value;
currentNode = currentNode.next;
}
return null;
}
}
HashTable.prototype.retrieveAll = function() {
let allNodes = [];
for (let i = 0; i < this.numBuckets; i++) {
let currentNode = this.buckets[i];
console.log('awal', currentNode);
while(currentNode) {
console.log('while', currentNode);
allNodes.push(currentNode);
currentNode = currentNode.next;
}
}
return allNodes;
}
let myHT = new HashTable(30);
myHT.insert('Dean', 'dean@gmail.com');
myHT.insert('Megan', 'megan@gmail.com');
myHT.insert('Dane', 'dane@yahoo.com');
myHT.insert('Dean', 'deanmachine@gmail.com');
myHT.insert('Megan', 'megansmith@gmail.com');
myHT.insert('Dane', 'dane1010@outlook.com');
console.log(myHT.get('Megan'));