-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathhash-table.js
71 lines (65 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
class HashTable {
constructor(size) {
this.table = new Array(size);
this.size = size;
}
hash(key) {
let total = 0;
for (let i = 0; i < key.length; i++) {
total += key.charCodeAt(i);
}
return total % this.size;
}
set(key, value) {
const index = this.hash(key);
const bucket = this.table[index];
if (!bucket) {
this.table[index] = [[key, value]];
} else {
const sameKeyItem = bucket.find((item) => item[0] === key);
if (sameKeyItem) {
sameKeyItem[1] = value;
} else {
bucket.push([key, value]);
}
}
}
get(key) {
const index = this.hash(key);
const bucket = this.table[index];
if (bucket) {
const sameKeyItem = bucket.find((item) => item[0] === key);
if (sameKeyItem) {
return sameKeyItem[1];
}
}
return undefined;
}
remove(key) {
let index = this.hash(key);
const bucket = this.table[index];
if (bucket) {
const sameKeyItem = bucket.find((item) => item[0] === key);
if (sameKeyItem) {
bucket.splice(bucket.indexOf(sameKeyItem), 1);
}
}
}
display() {
for (let i = 0; i < this.table.length; i++) {
if (this.table[i]) {
console.log(i, this.table[i]);
}
}
}
}
const table = new HashTable(10);
table.set("name", "Bruce");
table.set("age", 25);
table.display();
console.log(table.get("name"));
table.set("mane", "Clark");
table.set("name", "Diana");
console.log(table.get("mane"));
table.remove("name");
table.display();