JS数据结构和算法4

116 阅读1分钟

JS数据结构和算法

集合

  • 集合常见的实现方式:哈希表
  • 集合特点:无序、不允许重复

image.png

集合封装

  1. 集合常见操作

image.png

  1. 方法封装
<script>
    // 封装集合类
    function Set() {
      // 属性
      this.items = {};

      // add(data) 添加元素
      Set.prototype.add = function (data) {
        // 1. 判断是否存在
        if (this.has(data)) {
          return false
        }
        this.items[data] = data;
        return true;
      }

      // remove(data) 删除元素
      Set.prototype.remove = function (data) {
        if (!this.has(data)) {
          return false
        }
        delete this.items[data];
        return true;
      }

      // has(data) 判断集合是否含有该元素
      Set.prototype.has = function (data) {
        return this.items.hasOwnProperty(data);
      }

      // clear() 清除集合里的所有元素
      Set.prototype.clear = function () {
        this.items = {};
      }

      // size() 返回集合里元素的个数
      Set.prototype.size = function () {
        return Object.keys(this.items).length;
      }

      // values() 返回一个包含集合所有元素的数组
      Set.prototype.values = function (data) {
        return Object.keys(this.items)
      }

      // 并集
      Set.prototype.union = function (otherSet) {
        // 1. 创建新集合
        var unionSet = new Set();
        var values = this.values();
        for (var i = 0; i < values.length; i++) {
          unionSet.add(values[i])
        }
        var otherValues = otherSet.values();
        for (var i = 0; i < otherValues.length; i++) {
          unionSet.add(otherValues[i]);
        }
        return unionSet;
      }

      // 交集
      Set.prototype.intersection = function (otherSet) {
        // 1. 创建新集合
        var unionSet = new Set();
        var values = this.values();
        for (var i = 0; i < values.length; i++) {
          if (otherSet.has(values[i])) {
            unionSet.add(values[i]);
          }
        }
        return unionSet;
      }

      // 差集
      Set.prototype.difference = function (otherSet) {
        // 1. 创建新集合
        var unionSet = new Set();
        var values = this.values();
        for (var i = 0; i < values.length; i++) {
          if (!otherSet.has(values[i])) {
            unionSet.add(values[i]);
          }
        }
        return unionSet;
      }

      // 子集
      Set.prototype.subset = function (otherSet) {
        // this表示集合 A,otherSet表示集合B
        // 判断集合A是不是otherSet的子集
        var values = this.values();
        for (var i = 0; i < values.length; i++) {
          if (!otherSet.has(values[i])) {
            return false;
          }
        }
        return true;
      }
    }

    var set = new Set();
    set.add('a');
    set.add('b');
    set.add('c');
    console.log(set.remove('c'));
    console.log(set.has('a'));
    console.log(set.size());
    console.log(set.values());
    console.log(set.clear());
  </script>

字典

image.png

image.png

  1. 字典封装:跟集合很像,只是多了个键,模仿Map构造函数