集合

'use strict'

const md5 = require('blueimp-md5');

class Set {
    constructor() {
        this.items = {}
    }

    has(value) {
        return this.items.hasOwnProperty(md5(JSON.stringify(value)));
    }

    add(value) {
        const key = md5(JSON.stringify(value));
        if (!this.has(key)) {
            this.items[key] = value;
            return true;
        }
        return false;
    }

    remove(value) {
        const key = md5(JSON.stringify(value));
        if (this.has(key)) {
            delete this.items[key];
            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 value of values) {
            unionSet.add(value);
        }
        values = otherSet.values();
        for (let value of values) {
            unionSet.add(value);
        }
        return unionSet;
    }

    intersertion(otherSet) {
        let intersertionSet = new Set();
        for (let key in this.items) {
            if (otherSet.has(this.items[key])) {
                intersertionSet.add(this.items[key]);
            };
        }
        return intersertionSet;
    }

    difference(otherSet) {
        let differenceSet = new Set();
        for (let key in this.items) {
            if (!otherSet.has(this.items[key])) {
                differenceSet.add(this.items[key]);
            }
        }
        return differenceSet;
    }

    isSubset(otherSet) {
        if (this.size() > otherSet.size()) {
            return false;
        } else {
            for (let key in this.items) {
                if (!otherSet.has(this.items[key])) {
                    return false;
                }
            }
            return true;
        }
    }
}




const s = new Set();
const se = new Set();

s.add('2121');
s.add({ 'dede': 'dede' });
s.add({ 'dede': 'dede' });
se.add({ 'fee': 'fee' });
se.add('2121');

s.isSubset(se);
console.log(s.isSubset(se));
console.log(s.intersertion(se));
console.log(s.union(se).values());
console.log(s.difference(se).values());



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章