Hash Table - Hashing with Chaining
Incredibly, the Array.prototype.fill
will fill each item with the same Object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class Node { constructor(value) { this.next = null this.value = value } }
class Hash_Table { constructor(size = 16) { this.size = size this.data = new Array(this.size) for (let i = 0; i < this.size; i++) { this.data[i] = { next: null } } }
_hash(string) { let hash = 5381 string .toString() .split("") .map((i) => (hash = (hash << 5) + hash + i.charCodeAt(0))) return hash }
insert(key, value) { let pointer = this.data[this._hash(key) % this.size] if (!pointer.next) { pointer.next = new Node(value) } else { while (pointer.next) { pointer = pointer.next if (pointer.value === value) return } pointer.next = new Node(value) } }
get(key) { let pointer = this.data[this._hash(key) % this.size], result = [] if (!pointer.next) return new Error("Doesn't exist.") else { do { pointer = pointer.next result.push(pointer.value) } while (pointer.next)
return result } }
delete(key) { this.data[this._hash(key) % this.size] = { next: null } } }
let hash = new Hash_Table() hash.insert("test", 3) hash.insert("test", 5) hash.insert("test", 5) hash.insert("test", 6) hash.insert(12, 44) hash.insert(11, 3) hash.insert(10, 3) console.log(hash.get("test")) hash.delete(12) console.log(hash.get(12))
|
result:
1 2
| Array(3) [3, 5, 6] Error: Doesn't exist.
|