js:Set集合的实现

1.set集合的定义

         集合成员是无序的,是不重复的一组成员。

         开发中可用于去除重复数据

        set集合和map不一样。这里只实现了set集合的方法。

        map是用哈希结构的定义来实现的,本质上也是对数组和链的结合。

        方法就不介绍了,集合的定义数学都是学过的。

2.封装对象 

        此处用对象的方式来实现集合

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

 3.新增值

    默认set的健名是其健值

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

            this.items[value]=value
            return true
        }

 3.删除值

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

        Set.prototype.remove=function(value){
            if(!this.has(value)){
                return false
            }
            delete this.items[value]
            return true
        }

 4.一般方法

 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)
        }

5.并集 

 Set.prototype.union=function(otherSet){
            var unionSet=new Set()
            var values=this.values()
            for(var i=0;i<values.length;i++){
                unionSet.add(values[i])
            }
            values=otherSet.values()
            for(var i=0;i<values.length;o++){
                unionSet.add(values[i])
            }
            return unionSet
        }

 6.交集

 Set.prototype.intersection=function(otherSet){
            var intersectionSet=new Set()
            var values=this.values()
            for(var i=0;i<values.length;i++){
               var item=values[i]
               if(otherSet.has(item)){
                   intersectionSet.add(item)
               }
            }
           
            return intersectionSet
        }

7. 补集

  Set.prototype.difference=function(otherSet){
            var differenceSet=new Set()
            var values=this.values()
            for(var i=0;i<values.length;i++){
               var item=values[i]
               if(!otherSet.has(item)){
                differenceSet.add(item)
               }
            }
           
            return differenceSet
        }

8.子集 

 Set.prototype.subset=function(otherSet){
            
            var values=this.values()
            for(var i=0;i<values.length;i++){
               var item=values[i]
               if(!otherSet.has(item)){
                return false
               }
            }
           
            return true
        }

 

 

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值