|
| 1 | +/** |
| 2 | + * @author Rashik Ansar |
| 3 | + * |
| 4 | + * Implementation of Hash Table |
| 5 | + */ |
| 6 | + |
| 7 | +class HashTable { |
| 8 | + constructor(size = 47) { |
| 9 | + this.keyMap = new Array(size); |
| 10 | + } |
| 11 | + |
| 12 | + /** |
| 13 | + * Hash Function |
| 14 | + * Private method to generate hash of the given data |
| 15 | + * @param {*} key data to hash |
| 16 | + */ |
| 17 | + _hash(key) { |
| 18 | + let total = 0; |
| 19 | + const RANDOM_PRIME = 31; |
| 20 | + for (let i = 0; i < Math.min(key.length, 100); i++) { |
| 21 | + let char = key[i]; |
| 22 | + let value = char.charCodeAt(0) - 96; |
| 23 | + total = (total * RANDOM_PRIME + value) % this.keyMap.length; |
| 24 | + } |
| 25 | + return total; |
| 26 | + } |
| 27 | + |
| 28 | + set(key, value) { |
| 29 | + let index = this._hash(key); |
| 30 | + if (!this.keyMap[index]) { |
| 31 | + this.keyMap[index] = []; |
| 32 | + } |
| 33 | + this.keyMap[index].push([key, value]); |
| 34 | + return this; |
| 35 | + } |
| 36 | + |
| 37 | + get(key) { |
| 38 | + let index = this._hash(key); |
| 39 | + if (this.keyMap[index]) { |
| 40 | + for (let i = 0; i < this.keyMap[index].length; i++) { |
| 41 | + if (this.keyMap[index][i][0] === key) { |
| 42 | + return this.keyMap[index][i]; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + return undefined; |
| 47 | + } |
| 48 | + |
| 49 | + values() { |
| 50 | + let valArray = []; |
| 51 | + for (let i = 0; i < this.keyMap.length; i++) { |
| 52 | + if (this.keyMap[i]) { |
| 53 | + for (let j = 0; j < this.keyMap[i].length; j++) { |
| 54 | + if (!valArray.includes(this.keyMap[i][j][1])) { |
| 55 | + valArray.push(this.keyMap[i][j][1]); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + return valArray; |
| 61 | + } |
| 62 | + |
| 63 | + keys() { |
| 64 | + let keysArray = []; |
| 65 | + for (let i = 0; i < this.keyMap.length; i++) { |
| 66 | + if (this.keyMap[i]) { |
| 67 | + for (let j = 0; j < this.keyMap[i].length; j++) { |
| 68 | + if (!keysArray.includes(this.keyMap[i][j][0])) { |
| 69 | + keysArray.push(this.keyMap[i][j][0]); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + return keysArray; |
| 75 | + } |
| 76 | +} |
0 commit comments