Skip to content

Instantly share code, notes, and snippets.

@AlanD20
Created March 14, 2021 17:07
Show Gist options
  • Save AlanD20/f5f5e7ebd8791934379b00efafd4d196 to your computer and use it in GitHub Desktop.
Save AlanD20/f5f5e7ebd8791934379b00efafd4d196 to your computer and use it in GitHub Desktop.
Hash Table JS
function idk(key,size){
return [...key].map(x=>33*x.charCodeAt(0)%key.length).reduce((a,c)=>c+a);
}
console.log(idk('firstName', 113))
class table{
items = new Array(113);
setItem(key, value){
const idx= idk(key, this.items.length);
if(this.items[idx]){
this.items[idx].push([key, value])
}else{
this.items[idx] = [[key, value]];
}
}
getItem(key){
const idx = idk(key, this.items.length);
if(!this.items[idx]) return null;
return this.items[idx].find(x=>x[0] === key)[1];
}
}
const tb = new table();
tb.setItem('firstName', 'Johnny');
tb.setItem('mid', 'AlanD20');
tb.setItem('lastName', 'Timmy');
console.log(tb.getItem('firstName'));
console.log(tb.items);
//tut https://youtu.be/UOxTMOCTEZk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment