-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.js
More file actions
67 lines (62 loc) · 1.53 KB
/
Copy pathHashTable.js
File metadata and controls
67 lines (62 loc) · 1.53 KB
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
"use strict";
var hash = function(key, max) {
var hash = 0;
for (let i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
return hash % max;
};
let HashTable = function() {
let storage = [];
let storageLimit = 10;
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) {
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 (var 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];
}
}
}
};
};
let ht = new HashTable();
ht.add("a", "person");
ht.add("b", "dog");
ht.add("c", "dino");
ht.add("d", "Penguin");
ht.print();