-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHash_Table.js
86 lines (77 loc) · 2.11 KB
/
Hash_Table.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
77
78
79
80
81
82
83
84
85
86
/* Hash Table */
let hash = (string, max) => {
let hash = 0;
for (let i=0; i<string.length; i++) {
hash += string.charCodeAt(i);
}
return hash % max;
}
class HashTable {
constructor() {
this.storage = [];
this.storageLimit = 14;
}
print() {
console.log(this.storage);
}
add(key, value) {
let index = hash(key, this.storageLimit);
if (this.storage[index] === undefined) {
this.storage[index] = [
[key, value]
];
} else {
let inserted = false;
for (let i=0; i<this.storage[index].length; i++) {
if (this.storage[index][i][0] === key) {
this.storage[index][i][i] = value;
inserted = true;
}
}
if (inserted === false) {
storage[index].push([key, value]);
}
}
}
remove(key) {
let index = hash(key, this.storageLimit);
if (storage[index].length === 1 && storage[index][0][0] === key) {
delete storage[index];
} else {
for (let i=0; i<this.storage[index].length; i++) {
if (this.storage[index][i][0] === key) {
delete storage[index][i];
}
}
}
}
lookup(key) {
let index = hash(key, this.storageLimit);
if (this.storage[index] === undefined) {
return undefined;
} else {
for (let i=0; i<this.storage[index].length; i++) {
if (this.storage[index][i][0] === key) {
return this.storage[index][i][1];
}
}
}
}
}
console.log(hash('quincy', 10)); //5
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')); // penguin
ht.print();
/*
[ <3 empty items>,
[ [ 'tux', 'penguin' ] ],
<3 empty items>,
[ [ 'beau', 'person' ] ],
<4 empty items>,
[ [ 'fido', 'dog' ] ],
[ [ 'rex', 'dinosour' ] ] ]
* */