1.set集合的定义
集合成员是无序的,是不重复的一组成员。
开发中可用于去除重复数据
set集合和map不一样。这里只实现了set集合的方法。
map是用哈希结构的定义来实现的,本质上也是对数组和链的结合。
方法就不介绍了,集合的定义数学都是学过的。
2.封装对象
此处用对象的方式来实现集合
function Set(){
this.items={}
}
3.新增值
默认set的健名是其健值
Set.prototype.add=function(value){
if(this.has(value)){
return false
}
this.items[value]=value
return true
}
3.删除值
Set.prototype.has=function(value){
return this.items.hasOwnProperty(value)
}
Set.prototype.remove=function(value){
if(!this.has(value)){
return false
}
delete this.items[value]
return true
}
4.一般方法
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)
}
5.并集
Set.prototype.union=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(var i=0;i<values.length;o++){
unionSet.add(values[i])
}
return unionSet
}
6.交集
Set.prototype.intersection=function(otherSet){
var intersectionSet=new Set()
var values=this.values()
for(var i=0;i<values.length;i++){
var item=values[i]
if(otherSet.has(item)){
intersectionSet.add(item)
}
}
return intersectionSet
}
7. 补集
Set.prototype.difference=function(otherSet){
var differenceSet=new Set()
var values=this.values()
for(var i=0;i<values.length;i++){
var item=values[i]
if(!otherSet.has(item)){
differenceSet.add(item)
}
}
return differenceSet
}
8.子集
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
}