Skip to content

Instantly share code, notes, and snippets.

@darshna09
Created May 3, 2021 09:25
Show Gist options
  • Save darshna09/2125761292e5211a047c758484d8ac50 to your computer and use it in GitHub Desktop.
Save darshna09/2125761292e5211a047c758484d8ac50 to your computer and use it in GitHub Desktop.
Boilerplate code to implement hash tables in JavaScript.
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