<Day5- 集合>
從第一天到今天就是所有的循序資料結構
.size方法,有3種實作方式
Object.keys(items).length
//建立集合 ES6有set類別 自己實做一次看看
function Set(){
let items = {}
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.has = function(value){
//先做has(value),因為會被add, remove呼叫
//= return value in items
return items.hasOwnProperty(value)
}
this.clear = function(){
items = {}
}
this.size = function(){
return Object.keys(items).length
// let count = 0
// for(let prop in items){
// if(itmes.hasOwnProperty(prop))
// ++count
// }
// return count
}
this.values = function(){
return Object.keys(items)
// let keys = []
// for(let key in items){
// keys.push(key)
// }
// return keys
}
this.union = function(otherSet){
let unionSet = new Set()
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 Set()
let values = this.values()
for(let i = 0 ; i< values.length ; i++){
if(otherSet.has(values[i])){
intersectionSet.add(values[i])
}
}
return intersectionSet
}
this.difference = function(otherSet){
let differenceSet = new Set()
let values = this.values()
for(let i = 0 ; i< values.length ; i++){
if(!otherSet.has(values[i])){
differenceSet.add(values[i])
}
}
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
}
}
}
//使用
//集合操作