![]()
function Set() {
// 属性 不用数组 因为数组允许元素重复 集合是不重复的
this.items = {}
// 方法
Set.prototype.add = function(value) {
if (this.has(value)) { //对象中已经有了该元素 不需要添加了
return false
}
this.items[value] = value
return true
}
Set.prototype.has = function(value) {
return this.items.hasOwnProperty(value) //① hasOwnproperty
}
Set.prototype.remove = function(value) {
if (!this.has(value)) {
return false
}
delete this.items[value] //② delete对象元素
return true
}
Set.prototype.clear = function() {
this.items = {} //指向新对象 之前的因为没有指向 会自动清除
}
Set.prototype.size = function() {
return Object.keys(this.items).length // ③ Object.keys 返回一个所有元素为字符串的数组
}
Set.prototype.values = function() {
return Object.keys(this.items)
}
// 集合间的操作
// 并集
Set.prototype.union = function(otherSet) {
// this 集合A otherSet 集合B
// 创建新结合
var unionSet = new Set()
var values = this.values()
// 将A集合所有元素添加到新集合中
for(var i=0; i<values.length; i++) {
unionSet.add(values[i])
}
//
values = otherSet.values()
for (var i=0; i< values.length; i++) {
unionSet.add(values[i])
}
return unionSet
}
// 交集
Set.prototype.intersection = function(otherSet) {
// this 集合A otherSet 集合B
var intersection = new Set()
var values = this.values()
for(var i=0; i<values.length; i++) {
var item = values[i]
if (otherSet.has(item)) {
intersection.add(item)
}
}
return intersection
}
// 差集
Set.prototype.difference = function(otherSet) {
// this 集合A otherSet 集合B
var difference = new Set()
var values = this.values()
for(var i=0; i<values.length; i++) {
var item = values[i]
if (!otherSet.has(item)) {
difference.add(item)
}
}
return difference
}
Set.prototype.subset = function(otherSet) {
// this 集合A otherSet 集合B
// 判断集合A是不是集合B的子集
// 遍历集合A 如果发现集合A中元素在集合B中不存在 返回false
var values = this.values()
for (var i=0; i<values.length; i++) {
var item = values[i]
if (!otherSet.has(item)) {
return false
}
}
return true
}
}
// 创建Set
// var set = new Set()
// alert(set.add('abc'))
// alert(set.add('abc'))
// alert(set.add('cba'))
// alert(set.add('nba'))
// alert(set.add('mba'))
// alert(set.values())
// alert(set.remove('mba'))
// alert(set.remove('mba'))
// alert(set.values())
// alert(set.has('abc'))
// alert(set.size())
// set.clear()
// alert(set.size())
var setA = new Set()
setA.add('abc')
setA.add('cba')
setA.add('nba')
var setB = new Set()
setB.add('aaa')
setB.add('cba')
setB.add('nba')
var unionSet = setA.union(setB)
alert(unionSet.values())
var intersectionSet = setA.intersection(setB)
alert(intersectionSet.values())
// 求两个集合差集
var differenceSet = setA.difference(setB)
alert(differenceSet.values())
alert(setA.subset(setB))