JavaScript数据结构与算法之集合

70 阅读1分钟
// 集合
function Set() {
  this.items = {};
  this.length = 0;
  // 新增
  Set.prototype.add = function (value) {
    if (this.has(value)) {
      return false;
    }
    this.items[value] = value;
    this.length += 1;
  };
  // 删除
  Set.prototype.remove = function (value) {
    if (!this.has(value)) {
      return false;
    }
    // 当对象的属性为动态时,可以采用动态结构
    const { [value]: removeObj, ...otherObj } = this.items;
    this.items = { ...otherObj };
    this.length -= 1;
    return true;
  };
  // 判断元素是否在集合中
  Set.prototype.has = function (value) {
    return this.items.hasOwnProperty(value);
  };
  // 清空集合
  Set.prototype.clear = function () {
    this.items = {};
    this.length = 0;
  };
  // 获取集合的长度
  Set.prototype.size = function () {
    return this.length;
  };
  // 获取集合中所有数据的数组
  Set.prototype.values = function () {
    return Object.values(this.items);
  };
  // 并集
  Set.prototype.union = function (newSet) {
    const unionSet = new Set();
    let values = this.values();
    for (let i = 0; i < values.length; i++) {
      unionSet.add(values[i]);
    }

    values = newSet.values();
    for (let i = 0; i < values.length; i++) {
      unionSet.add(values[i]);
    }
    return unionSet;
  };
}

const set = new Set();
set.add(22);
set.add(223);
set.add(224);
set.add(225);

const newSet = new Set();
newSet.add(22);
newSet.add(223);
newSet.add(222342);
newSet.add(34534543);

console.log("set.union(newSet);", set.union(newSet).values());