集合

98 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

什么是集合?

  • 集合是一种不允许值重复顺序数据结构

创建数据集合

function Set(){
    this.items = {}
}

创建has方法,用于判断某个元素是否存在于集合中

    Set.prototype.has = function (value) {
        return this.items.hasOwnProperty(value)
    }

Object原型有hasOwnProperty方法,该方法返回一个表明对象是否具有特定属性的布尔值

添加元素add

Set.prototype.add = function(value){
        if(this.has(value)) return false

        this.items[value] = value

        return true
    }

先判断添加的值是否存在,如果不存在就添加进去,添加的时候,可以把它同时作为键和值保存,有利于查找一个元素

删除集合中某一个元素remove

Set.prototype.remove = function(value){
        if(!this.has(value)) return false

        delete this.items[value]

        return true
    }

先判断是否有这个元素,然后在通过delete来删除它的键,就可以实现删除该元素

清空集合

Set.prototype.clear = function(){
        this.items = {}
    }

获取集合的大小

Set.prototype.size = function(){
        return Object.keys(this.items).length
    }

获取集合内所有的值

Set.prototype.values = function(){
        return Object.keys(this.items)
    }

并集union

Set.prototype.union = function (otherSet) {
    const unionSet = new Set();

    let values = this.values();

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

    values = otherSet.values();

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

    return unionSet
  };

union方法不会修改原来的函数,没有副作用,被叫做纯函数

交集

Set.prototype.intersection = function(otherSet){
    const intersectionSet = new Set()

    const vualues= this.values()

    for(let i = 0;i < vualues.length;i++){
        if(otherSet.has(vualues[i])){
            intersectionSet.add(vualues[i])
        }
    }

    return intersectionSet
  }

和并集一样,它也是一个纯函数,不会对原函数产生影响

差集

Set.prototype.difference = function(otherSet){
      const differenceSet = new Set()

      this.values().forEach(value => {
          if(!otherSet.has(value)){
              differenceSet.add(value)
          }
      });

      return differenceSet
  }