Created
February 21, 2025 18:46
-
-
Save keif/9363e97c811a8e9f4a6d1b2c3a434bd0 to your computer and use it in GitHub Desktop.
In Javascript, create a hash table from scratch.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HashTable { | |
constructor(size = 53) { | |
this.buckets = Array.from({ length: size }, () => new Map()); // Use Map instead of arrays | |
this.size = size; | |
} | |
_hash = (key) => | |
[...key].reduce((acc, char) => (acc + char.charCodeAt(0) * 23) % this.size, 0); | |
set(key, value) { | |
this.buckets[this._hash(key)].set(key, value); // Directly store in Map | |
} | |
get = (key) => this.buckets[this._hash(key)].get(key); | |
delete(key) { | |
return this.buckets[this._hash(key)].delete(key); | |
} | |
keys = () => | |
this.buckets.flatMap((bucket) => [...bucket.keys()]); | |
values = () => | |
this.buckets.flatMap((bucket) => [...bucket.values()]); | |
} | |
// Example usage: | |
const ht = new HashTable(); | |
ht.set("name", "Alice"); | |
ht.set("age", 25); | |
ht.set("occupation", "Engineer"); | |
console.log(ht.get("name")); // Alice | |
console.log(ht.get("age")); // 25 | |
console.log(ht.delete("age")); // true | |
console.log(ht.get("age")); // undefined | |
console.log(ht.keys()); // ["name", "occupation"] | |
console.log(ht.values()); // ["Alice", "Engineer"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Map
provides O(1) average time complexity for insertions, lookups, and deletions.Set
is great for unique keys, but a hash table stores key-value pairs.Set
could be useful for a unique key store but wouldn't replace Map in this implementation.Set
wouldn’t be useful here since we need key-value storage, not just unique keys.