|
| 1 | +class HashTable { |
| 2 | + constructor(size) { |
| 3 | + this.table = new Array(size); |
| 4 | + this.size = size; |
| 5 | + } |
| 6 | + |
| 7 | + hash(key) { |
| 8 | + let total = 0; |
| 9 | + for (let i = 0; i < key.length; i++) { |
| 10 | + total += key.charCodeAt(i); |
| 11 | + } |
| 12 | + return total % this.size; |
| 13 | + } |
| 14 | + |
| 15 | + set(key, value) { |
| 16 | + const index = this.hash(key); |
| 17 | + const bucket = this.table[index]; |
| 18 | + if (!bucket) { |
| 19 | + this.table[index] = [[key, value]]; |
| 20 | + } else { |
| 21 | + const sameKeyItem = bucket.find((item) => item[0] === key); |
| 22 | + if (sameKeyItem) { |
| 23 | + sameKeyItem[1] = value; |
| 24 | + } else { |
| 25 | + bucket.push([key, value]); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + get(key) { |
| 31 | + const index = this.hash(key); |
| 32 | + const bucket = this.table[index]; |
| 33 | + if (bucket) { |
| 34 | + const sameKeyItem = bucket.find((item) => item[0] === key); |
| 35 | + if (sameKeyItem) { |
| 36 | + return sameKeyItem[1]; |
| 37 | + } |
| 38 | + } |
| 39 | + return undefined; |
| 40 | + } |
| 41 | + |
| 42 | + remove(key) { |
| 43 | + let index = this.hash(key); |
| 44 | + const bucket = this.table[index]; |
| 45 | + if (bucket) { |
| 46 | + const sameKeyItem = bucket.find((item) => item[0] === key); |
| 47 | + if (sameKeyItem) { |
| 48 | + bucket.splice(bucket.indexOf(sameKeyItem), 1); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + display() { |
| 54 | + for (let i = 0; i < this.table.length; i++) { |
| 55 | + if (this.table[i]) { |
| 56 | + console.log(i, this.table[i]); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +const table = new HashTable(10); |
| 63 | +table.set("name", "Bruce"); |
| 64 | +table.set("age", 25); |
| 65 | +table.display(); |
| 66 | +console.log(table.get("name")); |
| 67 | +table.set("mane", "Clark"); |
| 68 | +table.set("name", "Diana"); |
| 69 | +console.log(table.get("mane")); |
| 70 | +table.remove("name"); |
| 71 | +table.display(); |
0 commit comments