javascript数据结构——集合

javascript封装集合的内部方法

下面是集合所涉及的方法
javascript数据结构——集合_第1张图片

<script>
class Set {
      
  constructor() {
      
    this.item = {
      };
  }
  // 添加元素
  add(value) {
      
    if (this.has(value)) {
      
      return false;
    }
    this.item[value] = value;
    return true
  }
  // 判断是否存在某一个元素
  has(value) {
      
    return this.item.hasOwnProperty(value)
  }
  // 删除方法
  remove(value) {
      
    if (!this.has(value)) {
      
      return false;
    } else {
      
      delete this.item[value];
      return true;
    }
  }
  // 清除全部的数据
  clear() {
      
    this.item = {
      };
  }
  // 判断Set实例的长度
  size() {
      
    return Object.keys(this.item).length;
  }
  // 取出全部的值
  value() {
      
    return Object.keys(this.item);
  }
  // 去两个集合的并集操作
  union(set_b) {
      
    let unionSet = new Set();
    for (let i = 0; i < this.value().length; i++) {
      
      // console.log(this.value()[i]);
      unionSet.add(this.value()[i]);
    }
    for (let i = 0; i < set_b.value().length; i++) {
      
      //  console.log(set_b.value()[i]);
      unionSet.add(set_b.value()[i]);
    }
    return unionSet;
  }
  // 实现两个集合的交集的功能
  section(otherSet) {
      
    let sectionSet = new Set();
    for (let i = 0; i < this.value().length; i++) {
      
      if (otherSet.has(this.value()[i])) {
      
        sectionSet.add(this.value()[i]);
      }
    }
    return sectionSet;
  }
  // 实现两个集合的差集
  different(otherSet) {
      
    let sectionSet = new Set();
    for (let i = 0; i < this.value().length; i++) {
      
      if (!otherSet.has(this.value()[i])) {
      
        sectionSet.add(this.value()[i]);
      }
    }
    return sectionSet;
  }
  //判断两个集合的所属关系
  subSet(otherSet) {
      
    for (let i = 0; i < otherSet.value().length; i++) {
      
      if (!this.has(otherSet.value()[i])) {
      
        return false;
      }
    }
    return true;
  }
}

script>

你可能感兴趣的:(算法,数据结构,javascript,数据结构,集合,算法)