Javascript中的自定义哈希表实现



我是编程新手。我想用javascript实现一个简单的哈希表(用于教育目的(。一切都正常工作,除了当我试图覆盖某个值时,它保留了以前的值。例如,当我尝试hashTable.set(cherry,100(,然后hashTable_set(cherly,4(,再加上hashTable.get(cherry(时,我得到的是100,而不是4。我试着用调试器来检查它,但事实证明,如果您是编程新手,调试器并没有帮助。这是代码:

class HashTable {
constructor(size) {
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
const address = this._hash(key);
if (!this.data[address]) {
this.data[address] = [];
}
if (Array.isArray(this.data[address])) {
for (let arr of this.data[address].values()) {
if (arr[0] === key) {
const arr1 = arr[1];
arr[1] === value;
return;
}
}
}
this.data[address].push([key, value]);
}
get(key) {
const address = this._hash(key);
const currentNode = this.data[address];
if (currentNode) {
for (let arr of currentNode) {
if (arr[0] === key) {
return arr[1];
}
}
}
return undefined;
}
}
const myHashTable = new HashTable(2);
myHashTable.set("cherry", 100);
myHashTable.set("cherry", 4);
console.log(myHashTable.get("cherry")); // returns 100 instead of 4
myHashTable.set("peach", 9);
console.log(myHashTable.get("peach"));
myHashTable.set("apple", 2);
console.log(myHashTable.get("apple"));

class HashTable {
constructor(size) {
this.data = new Array(size);
}
_hash(key) {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
const address = this._hash(key);
if (!this.data[address]) {
this.data[address] = [];
}
for (let el of this.data[address]) {
if (el[0] === key) {
el[1] = value;
return;
}
}
this.data[address].push([key, value]);
}
get(key) {
const address = this._hash(key);
const currentNode = this.data[address];
if (currentNode) {
for (let arr of currentNode) {
if (arr[0] === key) {
return arr[1];
}
}
}
return undefined;
}
}
const myHashTable = new HashTable(2);
myHashTable.set("cherry", 100);
myHashTable.set("cherry", 4);
console.log(myHashTable.get("cherry")); // returns 100 instead of 4
myHashTable.set("peach", 9);
console.log(myHashTable.get("peach"));
myHashTable.set("apple", 2);
console.log(myHashTable.get("apple"));

你在set函数中做了一些奇怪的事情。这就是我所改变的。现在,它在address中查看this.data的元素,并检查第一个元素以确保密钥不相同。如果是这样,它只是更新值并提前返回。我想这就是你的想法。

为了使这成为一个更好的解决方案,我建议您为底层阵列添加一个容量,当密度达到某个百分比时,您可以增加底层阵列以减少哈希冲突。

最新更新