-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTables.html
More file actions
104 lines (73 loc) · 2.65 KB
/
HashTables.html
File metadata and controls
104 lines (73 loc) · 2.65 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class HashTable {
constructor(size = 50) {
this.size = size;
this.buckets = Array(this.size).fill(null).map(() => []);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.size;
}
return hash;
}
set(key, value) {
const index = this._hash(key);
const bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
const [bucketKey] = bucket[i];
if (bucketKey === key) {
bucket[i][1] = value;
return;
}
}
bucket.push([key, value]);
}
get(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
const [bucketKey, bucketValue] = bucket[i];
if (bucketKey === key) {
return bucketValue;
}
}
return undefined;
}
remove(key) {
const index = this._hash(key);
const bucket = this.buckets[index];
for (let i = 0; i < bucket.length; i++) {
const [bucketKey] = bucket[i];
if (bucketKey === key) {
bucket.splice(i, 1);
return true;
}
}
return false;
}
display() {
return this.buckets.filter(bucket => bucket.length > 0);
}
}
const hashTable = new HashTable();
hashTable.set('name', 'Faisal');
hashTable.set('age', 30);
hashTable.set('city', 'Lagos');
console.log(hashTable.get('name'));
console.log(hashTable.get('age'));
console.log(hashTable.get('city'));
hashTable.remove('age')
console.log(hashTable.get('age'))
console.log(hashTable.display());
</script>
</body>
</html>