ES6的Set类是怎么实现的(集合)

版权声明:转载请注明出处,欢迎交流哦! https://blog.csdn.net/zdhui_fly/article/details/81118796

Set类就是数据结构中的集合

Set类的基本操作的实现:

function Set(){
            var items = {}
            var length = 0;
            //判断元素是否存在
            this.has = function(val){
                return items.hasOwnProperty(val)
            }
            //增加操作
            this.add = function(val){
                if(!this.has(val)){
                    items[val] = val;
                    length++;
                    return true;
                }
                return false;
            }
            // 删除操作
            this.remove = function(val){
                if(this.has(val)){
                    delete items[val]
                    length-=1;
                    return true;                
                }
                return false;
            }
            // 清除
            this.clear = function(){
                items = {};
                length = 0
                return true
            }
            //获取大小
            this.size = function(){
                return length;
            }
            //获取属性
            this.values = function(){
                return Object.keys(items);
            }
        }    
        var set = new Set()
        set.add(1);set.add(2);set.add(3);set.add('a')        

其他操作 

求并集:

            this.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;i++){
                    unionSet.add(values[i])                   //放入另一个集合的元素
                }
                return unionSet;
            }

交集:

this.intersection = function(otherSet){
                var intersectionSet = new Set();//存放结果
                var values = this.values();
                for(var i = 0;i<values.length;i++){
                    if(otherSet.has(values[i])){             //只放入两个集合共有的元素
                        intersectionSet.add(values[i])
                    }
                }
                return intersectionSet;
            }

差集: 

         this.difference = function(otherSet){
                var differenceSet = new Set();//存放结果
                var values = this.values();
                for(var i = 0;i<values.length;i++){
                    if(!otherSet.has(values[i])){          //只放入集合otherSet中没有的
                        differenceSet.add(values[i])
                    }
                }
                return differenceSet;
            }

猜你喜欢

转载自blog.csdn.net/zdhui_fly/article/details/81118796
今日推荐