Skip to content

集合 #24

Open
Open
@funnycoderstar

Description

@funnycoderstar

JS实现

class Set {
    constructor() {
        this.items = {};
    }
    has(value) {
        return this.items.hasOwnProperty(value);
    }
    add(value) {
        if(!this.has(value)) {
            this.items[value] = value;
            return true;
        }
        return false;
    }
    remove(value) {
        if(this.has(value)) {
            delete this.items[value];
            return true;
        }
        return false;
    }
    clear() {
        this.items = {};
    }
    size() {
        return Object.keys(this.items).length;
    }
    values() {
        let values = [];
        for(let key in this.items) {
            if(this.items.hasOwnProperty(key)) {
                values.push(this.items[key])
            }
        }
        return values;
    }
    // 并集
    union(otherSet) {
        let unionSet = new Set();
        let values = this.values();
        for(let i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }
        values = otherSet.values();
        for(let i = 0; i < values.length; i++) {
            unionSet.add(values[i]);
        }
        return unionSet;
    }
    // 交集
    intersection(otherSet) {
        let intersectionSet = new Set();
        let values = this.values();
        for(let i = 0 ; i < values.length; i++) {
            if(otherSet.has(values[i])) {
                intersectionSet.add(values[i]);
            }
        }
        return intersectionSet;
    }
    // 差集
    difference(otherSet) {
        let differenceSet = new Set();
        let values = this.values();
        for(let i = 0; i < values.length; i++) {
            if(!otherSet.has(values[i])) {
                differenceSet.add(values[i]);
            }
        }
        return differenceSet;
    }
    // 子集
    subSet(otherSet) {
        if(this.size() > otherSet.size()) {
            return false;
        } else {
            let values = this.values();
            for(let i = 0; i < values.length; i++) {
                if(!otherSet.has(values[i])) {
                    return false;
                }
            }
            return true;
        }
    }
}
let setA = new Set();
setA.add(1);
setA.add(2);
setA.add(3);

let setB = new Set();
setB.add(2);
setB.add(3);

console.log(setA.subSet(setB));
console.log(setB.subSet(setA));

ES6中的Set

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions