Last active
August 15, 2020 21:21
-
-
Save JohnIrle/f40d8a983dd994da26e88e44c18036b4 to your computer and use it in GitHub Desktop.
Revisions
-
JohnIrle revised this gist
Aug 15, 2020 . 1 changed file with 4 additions and 4 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -55,10 +55,10 @@ class HashTable { } 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")) -
JohnIrle created this gist
Aug 15, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,66 @@ 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", "bob"); myTable.setItem("lastName", "lazar"); myTable.setItem("age", 5); myTable.setItem("dob", "1/2/3"); console.log(myTable.getItem("firstName")) console.log(myTable.getItem("lastName")) console.log(myTable.getItem("age")) console.log(myTable.getItem("dob"))