Skip to content

数据结构 字典

字典的实现

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

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;
js
// Dictionary.test.js
const Dictionary = require("./Dictionary.js");

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