class HashEntry {
constructor(key, value) {
this.key = key; // Key for the entry
this.value = value; // Value associated with the key
this.next = null; // Reference to the next entry in the chain
}
}
class HashTable {
constructor(slots = 10) {
this.slots = slots; // Number of slots in the hash table
this.size = 0; // Current number of entries
this.bucket = new Array(this.slots).fill(null); // Array of buckets
}
// Hash function
getIndex(key) {
return key % this.slots; // Compute index using modulo operation
}
// Add key-value pair
add(key, value) {
const index = this.getIndex(key); // Compute the hash index
const newEntry = new HashEntry(key, value);
if (this.bucket[index] === null) {
this.bucket[index] = newEntry; // Insert entry if bucket is empty
} else {
let current = this.bucket[index];
while (current !== null) {
if (current.key === key) { // Key already exists, update value
current.value = value;
return;
}
if (current.next === null) break; // Traverse to the end of the chain
current = current.next;
}
current.next = newEntry; // Add new entry at the end of the chain
}
this.size++; // Increment size
}
// Search for a key
search(key) {
const index = this.getIndex(key); // Compute the hash index
let current = this.bucket[index]; // Retrieve the chain at the index
while (current !== null) { // Traverse the chain
if (current.key === key) { // Key found
return current.value; // Return the associated value
}
current = current.next; // Move to the next entry
}
return null; // Key not found
}
// Delete a key-value pair
delete(key) {
const index = this.getIndex(key); // Compute the hash index
let current = this.bucket[index];
let prev = null;
while (current !== null) {
if (current.key === key) { // Key found
if (prev === null) {
this.bucket[index] = current.next; // Remove first entry
} else {
prev.next = current.next; // Skip the current entry
}
this.size--; // Decrement size
return true; // Successfully deleted
}
prev = current;
current = current.next; // Move to the next entry
}
return false; // Key not found
}
}
// Test the Hash Table implementation
const ht = new HashTable();
ht.add(1, "Educative");
ht.add(11, "JavaScript");
ht.add(21, "HashTable");
// Search for a key
console.log(ht.search(11)); // Output: JavaScript
// Delete a key
console.log(ht.delete(11)); // Output: true
// Try to search for the deleted key
console.log(ht.search(11)); // Output: null