Last active
August 15, 2020 21:21
-
-
Save JohnIrle/f40d8a983dd994da26e88e44c18036b4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| function hashStringToInt(s, tableSize) { | |
| let hash = 17; | |
| for (let i = 0; i < s.length; i++) { | |
| hash = (13 * hash * s.charCodeAt(i)) % tableSize | |
| } | |
| return hash; | |
| } | |
| class HashTable { | |
| table = new Array(3) | |
| numItems = 0; | |
| resize = () => { | |
| const newTable = new Array(this.table.length * 2); | |
| this.table.forEach(item => { | |
| if (item) { | |
| item.forEach(([key, value]) => { | |
| const idx = hashStringToInt(key, newTable.length); | |
| if (newTable[idx]) { | |
| newTable[idx].push([key, value]); | |
| } else { | |
| newTable[idx] = [[key, value]]; | |
| } | |
| }) | |
| } | |
| }) | |
| this.table = newTable | |
| } | |
| setItem = (key, value) => { | |
| this.numItems++; | |
| const loadFactor = this.numItems/this.table.length; | |
| if (loadFactor > .8) { | |
| // resize | |
| this.resize(); | |
| } | |
| const idx = hashStringToInt(key, this.table.length) | |
| if (this.table[idx]) { | |
| this.table[idx].push([key, value]); | |
| } else { | |
| this.table[idx] = [[key, value]]; | |
| } | |
| } | |
| getItem = (key) => { | |
| const idx = hashStringToInt(key, this.table.length) | |
| if (!this.table[idx]) { | |
| return null; | |
| } | |
| return this.table[idx].find(x => x[0] === key)[1]; | |
| } | |
| } | |
| const myTable = new HashTable(); | |
| myTable.setItem("firstName", "John"); | |
| myTable.setItem("lastName", "Irle"); | |
| myTable.setItem("age", 30); | |
| myTable.setItem("dob", "08/15/2020"); | |
| console.log(myTable.getItem("firstName")) | |
| console.log(myTable.getItem("lastName")) | |
| console.log(myTable.getItem("age")) | |
| console.log(myTable.getItem("dob")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment