集合是由一組無序且唯一(即不能重復)的項組成的睁搭。這個數(shù)據(jù)結構使用了與有限集合相同的數(shù)學概念,但應用在計算機科學的數(shù)據(jù)結構中。ES6也有原生Set類的實現(xiàn)。集合李包含下面這些方法:has乐埠、add、remove、clear丈咐、size瑞眼、values。同時兩個集合之間還會有這些操作:并集(union)扯罐、交集(interaction)负拟、差集(difference)、子集(subset)歹河。
Set類的實現(xiàn)
function MySet(){
let items={}
this.has=function(value){
return items.hasOwnProperty(value)
}
this.add=function(value){
if(this.has(value)){
items[value]=value
return true
}
return false
}
this.remove=function(value){
if(this.has(value)){
delete items[value]
return true
}
return false
}
this.clear=function(){
items={}
}
this.size=function(){
let keys=Object.keys(items)
return keys.length
}
this.values=function(){
let keys=Object.keys(items)
return keys.map(key=>items[key])
}
this.union=function(otherSet){ // 并集
let unionSet=new MySet()
let values=this.values()
for(let i=0;i<values.length;i++){
unionSet.add(values[i])
}
values=otherSet.values()
for(let i=0;i<values.length;i++){
unionSet.add(values[i])
}
return unionSet
}
this.intersection=function(otherSet){ // 交集
let intersectionSet=new MySet()
let values=this.values()
for(let value of values){
if(otherSet.has(value)){
intersectionSet.add(value)
}
}
return intersectionSet
}
this.difference=function(otherSet){ // 差集
let differenceSet=new MySet()
let values=this.values()
for(let value of values){
if(!otherSet.has(value)){
differenceSet.add(value)
}
}
return differenceSet
}
this.subset=function(otherSet){ // 子集
if(this.size()>otherSet.size()){
return false
}else{
let values=this.values()
for(let i=0;i<values.length;i++){
if(!otherSet.has(values[i])){
return false
}
}
return true
}
}
}
ES6 Set類的擴展
ES6實現(xiàn)了原生的Set類,不過它是基于數(shù)組的花吟。因此創(chuàng)建一個實例是這樣:new Set(arr)
秸歧。Set類里基本也包含了上面的一些方法,但是沒有類之間的操作衅澈。下面在原生的Set類基礎上實現(xiàn)擴展键菱。
Set.prototype.union=function(otherSet){
let unionSet=new Set()
for(let x of this){
unionSet.add(x)
}
for(let x of otherSet){
unionSet.add(x)
}
return unionSet
}
Set.prototype.intersection=function(otherSet){
let intersectionSet=new Set()
for (let x of this){
if(otherSet.has(x)){
intersectionSet.add(x)
}
}
return intersectionSet
}
Set.prototype.difference=function(otherSet){
let differenceSet=new Set()
for(let x of this){
if(!otherSet.has(x)){
differenceSet.add(x)
}
}
return differenceSet
}
Set.prototype.subset=function(otherSet){
if(this.size<otherSet.size){
return false
}
for(let x of this){
if(!otherSet.has(x)){
return false
}
}
return true
}