-
-
Save redrambles/ae272705cc2f135756048a5090965a0d to your computer and use it in GitHub Desktop.
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.size = size; | |
this.table = new Array(this.size); | |
} | |
//lame-ass hash | |
hashIt(key) { | |
let hash = 0; | |
for (const char of key.toString()){ | |
hash += key.charCodeAt(char) | |
} | |
// Grab an index between 0 and size of table - 1 | |
return hash % this.size; | |
}; | |
put(key, value) { | |
const index = this.hashIt(key); | |
this.table[index] = {[key]: value} | |
} | |
get(key) { | |
const index = this.hashIt(key); | |
if (this.table[index]){ | |
return this.table[index][key] | |
} else { | |
// ain't nothing there, friend | |
return -1 | |
} | |
} | |
remove(key) { | |
const index = this.hashIt(key); | |
if (this.table[index]){ | |
this.table[index] = {} | |
} else { | |
console.log(`The table doesn't currently contain key: ${key}.`) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment