JS 集合


集合 (SET)

定義

  • 集合是一組無序但彼此之間有一定關聯的成員構成的,每一個成員在集合眾只能出現一次
  • 無序的 {1,2,3,4,5}=={5,4,3,2,1}
  • 不包含任何成員的集合稱之為空集,全集則是包含一切可能成員的集合
  • 如果兩個集合的成員完全相同,則稱兩個集合完全相同
  • 如何一個集合的所有成員都屬於另外一個集合,則前一集合屬於后一集合的子集

集合操作

  • 並集,將兩個集合中的成員進行合並,得到一個新的集合
  • 交集,兩個集合中共同存在的成員組成一個新的集合
  • 補集,屬於一個集合而不屬於另外一個集合成員的組成的集合

代碼實現

function Set() {
this.dataStore = [];
this.add = add;
this.remove = remove;
this.size = size;
// 並集操作
this.union = union;
// 交集操作
this.intersect = intersect;
// 是否是子集
this.subset = subset;
// 補集
this.difference = difference;
this.show = show;
this.contains=contains;
}

function add(item) {
    if (this.dataStore.indexOf(item) > -1) {
        return false;
    } else {
        this.dataStore.push(item);
        return true;
    }
}


function remove(item) {
    var pos = this.dataStore.indexOf(item);
    if (pos > -1) {
        this.dataStore.splice(pos, 1);
        return true;
    }
    return false;
}

function size() {
    return this.dataStore.length;
}

function contains(item) {
    return this.dataStore.indexOf(item) > -1;
}

function show() {
    return this.dataStore;
}

// 並集
function union(set) {
    var tempSet = new Set();
    // 1:將當前的集合元素插入臨時集合
    this.dataStore.forEach(function (item) {
        tempSet.add(item);
    });
    set.dataStore.forEach(function (item) {
        if (!tempSet.contains(item)) {
            tempSet.add(item);
        }
    })
    return tempSet;
}

// 交集
function intersect(set) {
    var tempSet = new Set();
    var that = this;
    set.dataStore.forEach(function (item) {
        if (that.dataStore.indexOf(item)>-1) {
            tempSet.add(item);
        }
    })
    return tempSet;
}

// 是否子集
function subset(set) {
    return this.dataStore.every(function (item) {
        return set.dataStore.indexOf(item)>-1
    })
}

// 補集,產生一個集合,某個元素屬於一個集合不屬於另外一個集合
function difference(set){
    var tempSet=new Set();
    this.dataStore.forEach(function(item){
        if( !set.contains(item)){
        tempSet.add(item); 
        }
    })
    return tempSet;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM