javascript 数据结构

Javascript 集合

2018-08-06  本文已影响0人  ak1947

集合的特点是不包含重复元素,集合的元素通常无顺序之分。在系统编程中集合很常用,但是并非所有语言都原生支持集合。
集合的三条理论:


集合的js实现:

function Set() {
    this.dataStore = [ ];
    // operations
    this.add = add;
    this.remove = remove;
    this.size = size;
    this.union = union;
    this.intersect = intersect;
    this.subset = subset;
    this.difference = difference;
    this.show = show;
}

function add(data) {
    if (this.dataStore.indexOf(data) < 0) {
        this.dataStore.push(data);
        return true;
    }
    else {
        return false;
    }
}

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

function show() {
    return this.dataStore;
}

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

function union(set) {
    var tmp = new Set();
    for  each (var e in this.dataStore) {
        tmp.add(e);
    }
    for each (var e in set) {
        if (!tmp.contains(e)) {
            tmp.push(e);
        }
    }
    return tmp;
}

function subset(set) {
    if (this.size() > set.size()) {
        return false;
    }
    else {
        for each (var e in this.dataStore) {
            if (!set.contains(e)) {
                return false;
            }
        }
    }
    return true;
}

function size() {
    return this.dataStore.length;
}
// 返回 this - set
function difference(set) {
    var tmp = new Set();
    for each (var e1 in this.dataStore) {
        if (!set.contains(e1)) tmp.add(e1);
    }
    return tmp;
}
上一篇 下一篇

猜你喜欢

热点阅读