获取哈希表的值

Get a value of a HashTable

我正在制作一个 HashTable 作为示例并保存它以备不时之需,但是我 运行 遇到了一个问题,试图实现一个 returns true 或 false 的方法,以防万一value 属于 HashTable,因为它在对象数组中作为代码中的注释。

我试过 for 循环、.map 和 for of,但总是失败,如果有人能帮助我的话。

function HashTable () {
    this.buckets = [];
    this.numbuckets = 35;
}

HashTable.prototype.hash = function (key) {
    let suma = 0;
    for (let i = 0; i < key.length; i++) {
        suma = suma + key.charCodeAt(i);
    }
    return suma % this.numbuckets;
}

HashTable.prototype.set = function (key, value) {
    if (typeof key !== "string") {
        throw new TypeError ("Keys must be strings")
    } else {
        var index = this.hash(key);
        if(this.buckets[index] === undefined) {
            this.buckets[index] = {};
        }
        this.buckets[index][key] = value;
    }
}

HashTable.prototype.get = function (key) {
    var index = this.hash(key);
    return this.buckets[index][key];
}

HashTable.prototype.hasKey = function (key) {
    var index = this.hash(key);
    return this.buckets[index].hasOwnProperty(key)
}

HashTable.prototype.remove = function (key) {
    var index = this.hash(key);
    if (this.buckets[index].hasOwnProperty(key)) {
       delete this.buckets[index]
       return true;
    }
    return false;
}

HashTable.prototype.hasValue = function (value) {
    let result = this.buckets;
    result = result.flat(Infinity);
    
    return result // [{Name: Toni}, {Mame: Tino}, {Answer: Jhon}]
}

您可以使用 Object.values() 获取存储桶中所有属性的值。

function HashTable() {
  this.buckets = [];
  this.numbuckets = 35;
}

HashTable.prototype.hash = function(key) {
  let suma = 0;
  for (let i = 0; i < key.length; i++) {
    suma = suma + key.charCodeAt(i);
  }
  return suma % this.numbuckets;
}

HashTable.prototype.set = function(key, value) {
  if (typeof key !== "string") {
    throw new TypeError("Keys must be strings")
  } else {
    var index = this.hash(key);
    if (this.buckets[index] === undefined) {
      this.buckets[index] = {};
    }
    this.buckets[index][key] = value;
  }
}

HashTable.prototype.get = function(key) {
  var index = this.hash(key);
  return this.buckets[index][key];
}

HashTable.prototype.hasKey = function(key) {
  var index = this.hash(key);
  return this.buckets[index].hasOwnProperty(key)
}

HashTable.prototype.remove = function(key) {
  var index = this.hash(key);
  if (this.buckets[index].hasOwnProperty(key)) {
    delete this.buckets[index]
    return true;
  }
  return false;
}

HashTable.prototype.hasValue = function(value) {
  return this.buckets.some(bucket => Object.values(bucket).includes(value));
}

let h = new HashTable;
h.set("Abc", 1);
h.set("Def", 2);
console.log(h.hasValue(1));
console.log(h.hasValue(3));