Skip to content

Instantly share code, notes, and snippets.

@DNature
Created March 18, 2021 14:26
Show Gist options
  • Save DNature/982d2961ed3ff7b13b96676d3b50632b to your computer and use it in GitHub Desktop.
Save DNature/982d2961ed3ff7b13b96676d3b50632b to your computer and use it in GitHub Desktop.
Hash Table (Hash Map) using Javascript
function HashTable(){
this.table = new Array(3)
this.itemsLength = 0
this.hashStringToInt = (str, tableSize) => {
let hash = 13
for (let i = 0; i < str.length; i++){
hash = (13 * hash * str.charCodeAt(i))
}
return hash % tableSize
}
this.expandTable = () => {
const loadFactor = this.itemsLength / this.table.length;
if(loadFactor > 0.8){
const newTable = new Array(this.table.length * 2);
this.table.forEach(item => {
if (item) {
item.forEach(([key, value]) => {
const idx = this.hashStringToInt(key, newTable.length);
if (newTable[idx]) {
newTable[idx].push([key, value]);
} else {
newTable[idx] = [[key, value]];
}
});
}
});
this.table = newTable;
}
};
this.addItem = (key,value) => {
this.itemsLength++
this.expandTable();
const idx = this.hashStringToInt(key, this.table.length)
if(this.table[idx]){
this.table[idx].push([key, value])
} else {
this.table[idx] = [[key, value]]
}
}
this.getItem = key => {
const idx = this.hashStringToInt(key, this.table.length)
if(!this.table[idx]){
return undefined
}
return this.table[idx].find(x => x[0] === key)[1]
}
}
const myTable = new HashTable();
myTable.addItem("firstName", "bob");
myTable.addItem("lastName", "tim");
myTable.addItem("1", "divine");
myTable.addItem("age", 5);
myTable.addItem("dob", "1/2/3");
// console.log(myTable.getItem("firstName"));
// console.log(myTable.getItem("lastName"));
// console.log(myTable.getItem("age"));
// console.log(myTable.getItem("dob"));
console.table(myTable.table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment