集合的js实现
2017-11-23 本文已影响0人
infi_
function set(){
var items={}
this.has=function(value){
return items.hasOwnProperty(value)
}
this.add=function(value){
if(!this.has(value)){
items[value]=value
return true
}else{
return false
}
}
this.remove=function(value){
if(this.has(value)){
delete items[value]
return true
}else{
return false
}
}
this.clear=function(){
items={}
}
this.size=function(){
var count=0
for(var prop in items){
if(this.has(prop)){ //因为对象圆形还包含别的自带继承属性 用has保险
++count
}
}
return count
}
this.values=function(){
var keys=[]
for(var prop in items){
if(this.has(prop)){
keys.push(prop)
}
}
return keys
}
this.union=function(otherSet){ //合集
var unionSet=new set()
var values=this.values();
for(var i=0;i<values.length;i++){
unionSet.add(values[i])
}
var values=otherSet.values();
for(var i=0;i<values.length;i++){
unionSet.add(values[i])
}
return unionSet
}
this.intersection=function(otherSet){ //交集
var intersectionSet=new set()
var values=this.values()
for(var i=0;i<values.length;i++){
if(otherSet.has(values[i])){
intersectionSet.add(values[i])
}
}
return intersectionSet
}
this.unintersection=function(otherSet){ //差集
var intersectionSet=new set()
var values=this.values()
for(var i=0;i<values.length;i++){
if(!otherSet.has(values[i])){
intersectionSet.add(values[i])
}
}
return intersectionSet
}
this.son=function(otherSet){ //子集
if(this.size()>otherSet.size()){
return false
}else{
var values=this.values()
for(var i=0;i<values.length;i++){
if(!otherSet.has(values[i])){
return false
}
}
return true
}
}
}
var see=new set()
see.add(1)
see.add(2)
var see2=new set()
see2.add(1)
see2.add(5)
see2.add(7)
var see3=new set()
see3.add(5)
var ab=see.union(see2)
console.log(ab.values())
var cb=see.intersection(see2)
console.log(cb.values())
var cj=see.unintersection(see2)
console.log(cj.values())
console.log(see3.son(see))
console.log(see3.son(see2))