-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashTables.js
61 lines (59 loc) · 1.65 KB
/
HashTables.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
//implement associated arrays and mapping of key, value pair
//common way to implement map data structure and objects
//Time complexity : average is O(1) / worst case is O(n)
//has problem of collision = to solve it, just store both key and value there
let hash = (string, max) => {
let hash = 0;
for (let i = 0; i < string.length; i++) {
hash += string.charCodeAt(i);
}
return hash % max;
};
let HashTable = function () {
let storage = [];
const storageLimit = 4;
this.print = function () {
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]);
}
}
};
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].length; i++) {
if (storage[index][i][0] === key) {
delete storage[index][i];
}
}
}
};
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];
}
}
}
};
};