-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashtable.js
More file actions
63 lines (56 loc) · 1.6 KB
/
hashtable.js
File metadata and controls
63 lines (56 loc) · 1.6 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
class HashTable {
constructor(size = 10) {
this.size = size;
this.table = Array.from({ length: size }, () => []);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i)) % this.size;
}
return hash;
}
insert(key, value) {
const index = this._hash(key);
for (let pair of this.table[index]) {
if (pair[0] === key) {
pair[1] = value;
return;
}
}
this.table[index].push([key, value]);
}
get(key) {
const index = this._hash(key);
for (let pair of this.table[index]) {
if (pair[0] === key) {
return pair[1];
}
}
return `Key ${key} not found`;
}
remove(key) {
const index = this._hash(key);
for (let i = 0; i < this.table[index].length; i++) {
if (this.table[index][i][0] === key) {
this.table[index].splice(i, 1);
return;
}
}
return `Key ${key} not found`;
}
toString() {
return this.table.map(bucket => bucket.map(pair => `${pair[0]}: ${pair[1]}`).join(', ')).join(' | ');
}
}
// Example
const ht = new HashTable(5);
ht.insert("name", "Maria");
ht.insert("age", 25);
ht.insert("city", "Sao Paulo");
ht.insert("name", "Carlos");
console.log(`Hash Table: ${ht}`);
console.log(`Get 'name': ${ht.get('name')}`);
console.log(`Get 'city': ${ht.get('city')}`);
ht.remove("age");
console.log(`Hash Table after removing 'age': ${ht}`);