Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Search/HashTableSearch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* HashTable Search: https://en.wikipedia.org/wiki/Hash_table
*
* A hashtable, also known as a hash table or hash map, is a data structure that allows you to store and retrieve values using a key.
* It is an efficient way to implement a dictionary-like data structure where you can quickly access values based on their associated keys.
* Hashtable search involves using the key to locate the corresponding value in the hashtable.
*/

class HashTable {
constructor() {
this.table = {};
}

// Function to hash the key
hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash += key.charCodeAt(i);
}
return hash;
}

// Function to insert a key-value pair into the hashtable
insert(key, value) {
const index = this.hash(key);
this.table[index] = value;
}

// Function to search for a value by key
search(key) {
const index = this.hash(key);
return this.table[index];
}

// Function to remove a key-value pair from the hashtable
remove(key) {
const index = this.hash(key);
if (this.table[index]) {
delete this.table[index];
}
}
}

module.exports = HashTable;
30 changes: 30 additions & 0 deletions Search/test/HashTableSearch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import HashTable from "../HashTableSearch";

test('Inserting and searching for values in the hashtable', () => {
const hashtable = new HashTable();

// Insert key-value pairs
hashtable.insert("name", "Ambrish");
hashtable.insert("age", 26);
hashtable.insert("city", "India");

// Search for values and expect them to be correct
expect(hashtable.search("name")).toBe("Ambrish");
expect(hashtable.search("age")).toBe(26);
expect(hashtable.search("city")).toBe("India");

// Search for a non-existent key and expect it to be undefined
expect(hashtable.search("country")).toBeUndefined();
});

test('Removing values from the hashtable', () => {
const hashtable = new HashTable();

// Insert a key-value pair
hashtable.insert("name", "Ambrish");

// Remove the key-value pair and expect it to be undefined
hashtable.remove("name");
expect(hashtable.search("name")).toBeUndefined();
});