Skip to content

Commit 3be6003

Browse files
authored
Create HashTable.js
1 parent 3d31b07 commit 3be6003

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

03-DataStructures/HashTable.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class HashTable {
2+
constructor(size = 50) {
3+
this.size = size;
4+
this.buckets = new Array(size);
5+
}
6+
7+
// Hash function
8+
_hash(key) {
9+
let hash = 0;
10+
for (const char of key) {
11+
hash = (hash + char.charCodeAt(0)) % this.size;
12+
}
13+
return hash;
14+
}
15+
16+
// Set a key-value pair in the hash table
17+
set(key, value) {
18+
const index = this._hash(key);
19+
if (!this.buckets[index]) {
20+
this.buckets[index] = [];
21+
}
22+
this.buckets[index].push([key, value]);
23+
}
24+
25+
// Get the value associated with a key
26+
get(key) {
27+
const index = this._hash(key);
28+
if (!this.buckets[index]) {
29+
return null;
30+
}
31+
32+
for (const [storedKey, value] of this.buckets[index]) {
33+
if (storedKey === key) {
34+
return value;
35+
}
36+
}
37+
return null;
38+
}
39+
40+
// Other hash table operations (remove, update, etc.) can be added here
41+
}
42+
43+
// Example usage:
44+
const hashTable = new HashTable();
45+
46+
hashTable.set('firstName', 'John');
47+
hashTable.set('lastName', 'Doe');
48+
hashTable.set('age', 30);
49+
50+
console.log(hashTable.get('firstName')); // Output: 'John'
51+

0 commit comments

Comments
 (0)