-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.js
70 lines (63 loc) · 1.63 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
/**Hash Table */
let hash = (string, max) => {
let hash = 0;
for (let i = 0; i < string.length; i++) {
hash += string.charCodeAt(i);
}
return hash % max;
}
const HashTable = function() {
let storage = [];
const storageLimit = 4;
this.print = () => console.log(storage);
this.add = function(key, value) {
let index = hash(key, storageLimit);
if(storage[index] === undefined) {
storage[index] = [
[key, value]
];
} else {
let inserted = false;
for (let i = 0; i < storage[index].length; i++) {
if (storage[index][i][0] === key) {
storage[index][i][1] = value;
inserted = true;
}
}
if (inserted === false) {
storage[index].push([key, value]);
}
}
}// End add
this.remove = function(key) {
let index = hash(key, storageLimit);
if (storage[index].length === 1 && storage[index][0][0] === key) {
delete storage[index];
} else {
for (let i = 0; i < storage[index]; i++) {
if (storage[index][i][0] == key) {
delete storage[index][i];
}
}
}
}// End remove
this.lookup = function(key) {
let index = hash(key, storageLimit);
if (storage[index] === undefined) {
return undefined;
} else {
for (let i = 0; i < storage[index].length; i++) {
if (storage[index][i][0] == key) {
return storage[index][i][1];
}
}
}
}// End lookup
}// End HashTable
let ht = new HashTable();
ht.add('beau', 'person');
ht.add('fido', 'dog');
ht.add('rex', 'dinosour');
ht.add('tux', 'penguin');
console.log(ht.lookup('tux'));
ht.print();