Created
May 3, 2021 09:25
-
-
Save darshna09/2125761292e5211a047c758484d8ac50 to your computer and use it in GitHub Desktop.
Boilerplate code to implement hash tables in JavaScript.
This file contains 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) { | |
this.data = new Array(size); | |
} | |
// Hash Function | |
_hash(key) { | |
let hash = 0; | |
for (let i = 0; i < key.length; i++) { | |
hash = (hash + key.charCodeAt(i) * i) % this.data.length; | |
} | |
return hash; | |
} | |
// Insert key-value pair | |
set () {} | |
// Lookup a key | |
get () {} | |
// Return all the keys in the object. | |
keys () {} | |
} | |
const myHashTable = new HashTable(50); | |
myHashTable.set('has_garden', true); | |
myHashTable.get('has_garden'); // true | |
myHashTable.set('house_number', 54); | |
myHashTable.get('house_number'); // 54 | |
myHashTable.set('street_name', 'Main Street'); | |
myHashTable.get('street_name'); // 'Main Street' | |
myHashTable.keys(); // [ 'has_garden', 'house_number', 'street_name' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment