# 数据结构 字典

# 字典的实现

字典的实现需要用到哈希表,由于 JS 中的对象就是一个哈希表,这里我们直接使用对象多为哈希表

function Dictionary() {
  const items = {};

  this.set = function (key, value) {
    items[key] = value;
  };
  this.get = function (key) {
    if (this.has(key)) {
      return items[key];
    } else {
      return undefined;
    }
  };
  this.has = function (key) {
    return items.hasOwnProperty(key);
  };
  this.remove = function (key) {
    if (this.has(key)) {
      delete items[key];
      return true;
    } else {
      return false;
    }
  };

  this.keys = function () {
    return Object.keys(items);
  };
  this.values = function () {
    return Object.keys(items).map((key) => {
      return items[key];
    });
  };
  this.size = function () {
    return this.values().length;
  };
  this.getItems = function () {
    return items;
  };
}

module.exports = Dictionary;
// Dictionary.test.js
const Dictionary = require("./Dictionary.js");

const dic = new Dictionary();
dic.set("bob", "[email protected]");
dic.set("tom", "[email protected]");
dic.set("john", "[email protected]");
console.log(dic.has("bob")); // true
console.log(dic.size()); // 3
console.log(dic.get("bob")); // [email protected]
dic.remove("bob");
console.log(dic.get("bob")); // undefined
console.log(dic.size()); // 2
console.log(dic.keys()); // [ 'tom', 'john' ]
console.log(dic.values()); // [ '[email protected]', '[email protected]' ]
console.log(dic.getItems()); // { tom: '[email protected]', john: '[email protected]' }