js 集合实现

135 阅读1分钟

集合概念:集合是由无序且唯一(即不能重复)的项组成。

 现在的方式是采用创建类来做的。

其对应的方法有交集(intersect),并集(unionCollection),差集(difference),子集(subSet)。

Set作为基础数据类型。

class Collection {    
    constructor(data) {        
        this.collection = new Set(data);    
    }

    add(data) {        
        this.collection.add(data);    
    }

    get() {        
        return this.collection;    
    }

    remove(data) {        
        this.collection.remove(data);    
    }

    has(data) {        
        return this.collection.has(data);    
    }

    size() {        
        return this.collection.size;    
    }

    values(){        
        return this.collection;    
    }

    unionCollection(collection) {        
        let arr1 = Array.from(collection);        
        let arr2 = Array.from(this.collection);        
        return new Set(arr1.concat(arr2));    
    }

    intersect(collection) {        
        let arr = new Set();        
        this.collection.forEach(element => {            
            if (collection.has(element)) {                
                arr.add(element);            
            }        
        });        
        return arr;    
    }

    difference(collection) {        
        let arr = new Set();        
        this.collection.forEach(element => {            
            if (!collection.has(element)) {                
                arr.add(element);            
            }        
        });        
        return arr;    
    }

    subSet(collection) {        
        if (this.size() < collection.size()) {            
            return false;        
        } else {            
            let res = true;            
            collection.values().forEach(element=>{                
                if(!this.collection.has(element)){                    
                    res = false;                
                }            
            });            
            return res;        
        }    
    }
}

let test1 = new Collection([1, 2, 3, 4, 5, 6]);
let test2 = new Collection([4, 5, 6]);
console.log(test1.unionCollection(test2));
console.log(test1.intersect(test2));
console.log(test1.difference(test2));
console.log(test1.subSet(test2));

结果为: