|
| 1 | +function hashStringToInt(str, tableSize) { |
| 2 | + let hash = 17; |
| 3 | + |
| 4 | + for (let i = 0; i < str.length; i++) { |
| 5 | + hash = (13 * hash * str.charCodeAt(i)) % tableSize; |
| 6 | + } |
| 7 | + |
| 8 | + return hash; |
| 9 | +} |
| 10 | + |
| 11 | +class HashTable { |
| 12 | + table = new Array(3); |
| 13 | + numItems = 0; |
| 14 | + |
| 15 | + resize = () => { |
| 16 | + const newTable = new Array(this.table.length * 2); |
| 17 | + this.table.forEach(item => { |
| 18 | + if (item) { |
| 19 | + item.forEach(([key, value]) => { |
| 20 | + const idx = hashStringToInt(key, newTable.length); |
| 21 | + if (newTable[idx]) { |
| 22 | + newTable[idx].push([key, value]); |
| 23 | + } else { |
| 24 | + newTable[idx] = [[key, value]]; |
| 25 | + } |
| 26 | + }); |
| 27 | + } |
| 28 | + }); |
| 29 | + this.table = newTable; |
| 30 | + }; |
| 31 | + |
| 32 | + setItem = (key, value) => { |
| 33 | + this.numItems++; |
| 34 | + const loadFactor = this.numItems / this.table.length; |
| 35 | + |
| 36 | + if (loadFactor > 0.1) { |
| 37 | + // resize the table |
| 38 | + this.resize(); |
| 39 | + } |
| 40 | + |
| 41 | + const idx = hashStringToInt(key, this.table.length); |
| 42 | + if (this.table[idx]) { |
| 43 | + this.table[idx].push([key, value]); |
| 44 | + } else { |
| 45 | + this.table[idx] = [[key, value]]; |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + getItem = key => { |
| 50 | + const idx = hashStringToInt(key, this.table.length); |
| 51 | + return this.table[idx].find(x => x[0] === key)[1]; |
| 52 | + // the Array.prototype.find() returns the first element in the array satisfies the test function |
| 53 | + }; |
| 54 | +} |
| 55 | + |
| 56 | +const newHashTable = new HashTable(); |
| 57 | + |
| 58 | +newHashTable.setItem("lastName", "tim"); |
| 59 | +newHashTable.setItem("firstName", "bob"); |
| 60 | +newHashTable.setItem("age", 24); |
| 61 | +newHashTable.setItem("dob", "2/2/2"); |
| 62 | +// newHashTable.setItem("adress", "123/123/123"); |
| 63 | +console.log(newHashTable.getItem("firstName")); |
| 64 | +console.log(newHashTable.getItem("lastName")); |
| 65 | +console.log(newHashTable.getItem("dob")); |
| 66 | +console.log(newHashTable.table.length); |
| 67 | +console.log(newHashTable.table); |
0 commit comments