JavaScript——集合结构
function Set(){
this.items = {}
Set.prototype.has = function(value){
return this.items.hasOwnProperty(value)
}
Set.prototype.add = function(value){
if (this.has(value)){
return false
}
this.items[value] = value
return true
}
Set.prototype.remove = function(value){
if (this.has(value) == false){
return false
}
delete this.items[value]
return true
}
Set.prototype.clear = function(){
this.items = {}
}
Set.prototype.size = function(){
return Object.keys(this.items).length
}
Set.prototype.values = function(){
return Object.keys(this.items)
}
Set.prototype.union = function(otherSet){
let unionSet = new Set()
let values = this.values()
for (let i = 0; i < this.size(); i++){
unionSet.add(values[i])
}
values = otherSet.values()
for (let i = 0; i < otherSet.size(); i++){
unionSet.add(values[i])
}
return unionSet
}
Set.prototype.intersection = function(otherSet){
let intersection = new Set()
let values = this.values()
for (let i = 0; i < this.size(); i++){
if (otherSet.has(values[i])){
intersection.add(values[i])
}
}
return intersection
}
Set.prototype.difference = function(otherSet){
let difference = new Set()
let values = this.values()
for (let i = 0; i< this.size(); i++){
if (otherSet.has(values[i]) == false){
difference.add(values[i])
}
}
return difference
}
Set.prototype.isSubset = function(otherSet){
if (this.size() > otherSet.size()){
return false
}
let values = this.values()
for (let i =0; i < this.size(); i++){
if (otherSet.has(values[i]) == false){
return false
}
}
return true
}
}