javaScript 数据结构之集合&字典

集合set是一种包含不同元素的数据结构。集合中的元素成为成员。集合的两个最重要特性是:集合中的成员是无序的;集合中不允许相同成员存在
计算机中的集合与数学中集合的概念相同,不包含任何成员的集合称为空集;包含一切可能的成员为全集如果两个成员完全相同,则称为两个集合相等

集合的实现 :

function Set() {
  let items = {};
  this.has = function(value){
    return value in items;
  };
  this.add = function(value){
    if (!this.has(value)){
      items[value] = value; //{1}
      return true;
    }
    return false;
  };
  this.remove = function(value){
    if (this.has(value)){
      delete items[value]; //{2}
      return true;
    }
    return false;
  };
  this.clear = function(){
    items = {}; // {3}
  };
  this.size = function(){
    return Object.keys(items).length; //{4}
  };
  this.valuesLegacy = function(){
    let values = [];
    for(let key in items) { //{7}
      if(items.hasOwnProperty(key)) { //{8}
        values.push(items[key]);
      }
    }
  return values;
  };
  this.values = function(){
    let values = [];
    for (let i=0, keys=Object.keys(items); i<keys.length; i++) {
      values.push(items[keys[i]]);
    }
    return values;
  };
  this.values_sample =  function () {
    return Object.values(items);
  }
}

以上就是集合的大概是实现 和别的数据结构的实现都差不多 明天来补集合特有的交集并集子集等的实现

子集

// 子集
isSubsetOf(otherSet) {
  if (this.size() > otherSet.size()) return false;

  const values = this.values();
  for (let i = 0; i < values.length; i += 1) {
    const item = values[i];
    if (!otherSet.has(item)) return false;
  }

  return true;
}

交集

// 交集
intersection(otherSet) {
  const intersectionSet = new Set();

  const values = this.values();
  values.forEach(item => {
    if (otherSet.has(item)) {
      intersectionSet.add(item);
    }
  })

  return intersectionSet;
}

并集

// 并集
union(otherSet) {
  const unionSet = new Set();

  const values = this.values();
  values.forEach(item => unionSet.add(item));

  const otherValues = otherSet.values();
  otherValues.forEach(item => unionSet.add(item));

  return unionSet;
}

字典

集合表示一组互不相同的元素(不重复的元素)。在字典中,存储的是键-值对,其中键名是用来查询特定元素的。字典和集合很相似,集合以值-值对的形式存储元素,字典则是以键-值对的形式来存储元素。字典也称作映射

class Dictionary {
  constructor() {
    this._table = {};
    this._length = 0;
  }

  set(key, value) {
    if (!this.has(key)) {
      this._length += 1;
    }
    this._table[key] = value;
  }

  has(key) {
    return this._table.hasOwnProperty(key);
  }

  remove(key) {
    if (this.has(key)) {
      delete this._table[key];
      this._length -= 1;
      return true;
    }
    return false;
  }

  get(key) {
    return this._table[key];
  }

  clear() {
    this._table = {};
    this._length = 0;
  }

  size() {
    return this._length;
  }

  keys() {
    return Object.keys(this._table);
  }

  values() {
    return Object.values(this._table);
  }
}

猜你喜欢

转载自blog.csdn.net/qaqLjj/article/details/87395073