-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.js
More file actions
51 lines (42 loc) · 1.15 KB
/
HashTable.js
File metadata and controls
51 lines (42 loc) · 1.15 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
class HashTable {
constructor(size = 50) {
this.size = size;
this.buckets = new Array(size);
}
// Hash function
_hash(key) {
let hash = 0;
for (const char of key) {
hash = (hash + char.charCodeAt(0)) % this.size;
}
return hash;
}
// Set a key-value pair in the hash table
set(key, value) {
const index = this._hash(key);
if (!this.buckets[index]) {
this.buckets[index] = [];
}
this.buckets[index].push([key, value]);
}
// Get the value associated with a key
get(key) {
const index = this._hash(key);
if (!this.buckets[index]) {
return null;
}
for (const [storedKey, value] of this.buckets[index]) {
if (storedKey === key) {
return value;
}
}
return null;
}
// Other hash table operations (remove, update, etc.) can be added here
}
// Example usage:
const hashTable = new HashTable();
hashTable.set('firstName', 'John');
hashTable.set('lastName', 'Doe');
hashTable.set('age', 30);
console.log(hashTable.get('firstName')); // Output: 'John'