JavaScript数据结构与算法Day8(集合的封装)

120 阅读1分钟

集合属性封装

function Set() {
            this.items = {}
            }

add方法

Set.prototype.add = function (value) {
                if (this.has(value)) return false
                this.items[value] = value
                return true
            }

has方法

Set.prototype.has = function (value) {
                return this.items.hasOwnProperty(value)
            }

remove方法

Set.prototype.remove = function (value) {
                if (!this.has(value)) return false
                delete this.items[value]
                return true
            }

size方法

Set.prototype.size = function () {
                return Object.keys(this.items).length
            }

clear方法

Set.prototype.clear = function () {
                this.items = {}
            }

values方法

Set.prototype.values = function () {
                return Object.keys(this.items)
            }

unions方法

Set.prototype.unions = function (otherSet) {
                var unionSet = new Set()
                var values = this.values()
                for (var i = 0; i < values.length; i++) {
                    unionSet.add(values[i])
                }
                values = otherSet.values()
                for (i = 0; i < values.length; i++) {
                    unionSet.add(values[i])
                }
                return unionSet
            }

intersection方法

Set.prototype.intersection = function (otherSet) {
                var values = this.values()
                var intersectionSet = new Set()
                for (var i = 0; i < values.length; i++) {
                    var item = values[i]
                    if (otherSet.has(item)) {
                        intersectionSet.add(item)
                    }
                }
                return intersectionSet
            }

difference方法

Set.prototype.difference = function (otherSet) {
                var values = this.values()
                var diffSet = new Set()
                for (var i = 0; i < values.length; i++) {
                    var item = values[i]
                    if (!otherSet.has(item)) {
                        diffSet.add(item)
                    }
                }
                return diffSet
            }

subset方法

Set.prototype.subset = function (otherSet) {
                var values = this.values()
                for (var i = 0; i < values.length; i++) {
                    var item = values[i]
                    if (!otherSet.has(item)) {
                        return false
                    }
                    return true
                }
            }