JS數據結構初識-集合

1、定義

集合是由一組無序且惟一(即不能重複)的項組成的。這個數據結構使用了與有限集合相同 的數學概念,但應用在計算機科學的數據結構中。咱們使用對象而不是數組來表示集合。數組

2、實現

function Set() {
        const items = {};
        this.add = function(value) {
            if (this.has(value)) {
                return false;
            }
            const key = this.setKey(value);
            items[key] = value;
            return true;
        };
        this.remove = function(value) {
            if (!this.has(value)) {
                return false;
            }
            const key = this.setKey(value);
            delete(key);
        };
        this.clear = () => {
            items = {};
            return true;
        };
        this.size = () => Object.keys(items);
        this.values = () => Object.values(items);
        this.has = (value) => items.hasOwnProperty(value);
        this.setKey = (value) =>  `${typeof(value)}_${value}`;

        // 交集
        this.intersection = function(otherSet) {
            const intersectionSet = new Set();
            this.values().forEach((item) => {
                if (otherSet.has(item)) {
                    intersectionSet.add(item);
                }
            });
            return intersectionSet;
        }

        // 差集
        this.difference = function(otherSet) {
            const differenceSet = new Set();
            this.values().forEach((item) => {
                if (!otherSet.has(item)) {
                    differenceSet.add(item);
                }
            })
        }

        // 並集
        this.union = (otherSet) => ({  ...items, ...otherSet });

        // 子集 A是B的子集
        this.subset = function(otherSet) {
            if (this.size() > otherSet.size()) {
                return false;
            }
            const temp = this.values().find((item) => !otherSet.has(item));
            return !!temp;
        }
    }
複製代碼
相關文章
相關標籤/搜索