/
hash-table.js
85 lines (64 loc) · 1.52 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
const storage = [];
const hash = (str) => {
let h = 0;
const sl = str.length;
if (sl === 0) {
return h;
}
for (let i = 0; i < sl; i++) {
h = (h << 1) + str.charCodeAt(i);
}
return h;
};
class HashTable {
add(key, value) {
const index = hash(key);
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].push(key);
storage[index][i].push(value);
inserted = true;
}
}
if (inserted === false) {
storage[index].push([key, value]);
}
}
};
remove(key) {
var index = hash(key);
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];
}
}
}
};
find(key) {
var index = hash(key);
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];
}
}
}
};
};
const ht = new HashTable();
ht.add('Alex', '123-3455');
ht.add('Jhon', '252-2342');
ht.add('Jhon', '535-8898');
ht.add('Bob', '123-8635');
ht.add('Jake', '543-1243');
console.log(ht.find('Bob'));
console.log(storage);