forked from kloklo90/LeetcodeChallenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashtable.js
75 lines (68 loc) · 1.78 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
var hash = (string, max) => {
var hash = 0;
for (var i = 0; i < string.length; i++) {
hash += string.charCodeAt(i);
}
return hash % max;
};
let HashTable = function() {
let storage = [];
const storageLimit = 4; // Number of buckets in the array
this.print = function() {
console.log(storage);
}
this.add = function(key, value) {
var index = hash(key, storageLimit);
if(storage[index] === undefined) {
storage[index]= [
[key, value]
];
} else {
var inserted = false;
for (var 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) {
var index = hash(key, storageLimit);
if (storage[index].length === 1 && storage[index][0][0] === key) {
delete storage[index];
} else {
for (var i = 0; i < storage[index]; i++) {
if (storage[index][i][0] === key) {
delete storage[index][i];
}
}
}
};
this.lookup = function(key) {
var index = hash(key, storageLimit);
if (storage[index] === undefined) {
return undefined;
} else {
for (var i= 0; i < storage [index].length; i++) {
if (storage[index][i][0] === key) {
return storage[index][i][1];
}
}
}
};
};
//This Hash table will return a number between 0 and 9. as we have number 10 as
//the max number of buckets
console.log(hash('beau', 10));
console.log(hash('quincy', 10));
let ht = new HashTable();
ht.add('beau', 'person');
ht.add('fido', 'dog');
ht.add('rex', 'dinosaur');
ht.add('tux', 'penguin');
console.log(ht.lookup('tux'));
ht.print();