JavaScript——集合結構

JavaScript——集合結構

//集合類
function Set(){
	//存放集合中的屬性
	this.items = {}
	/*
	* 1. has方法,判斷集合中是否包含指定屬性
	*/ 
	Set.prototype.has = function(value){
		return this.items.hasOwnProperty(value)
	}
	/*
	* 2. add方法,添加一個新的屬性
	*/ 
	Set.prototype.add = function(value){
		//判斷是否已經存在此屬性
		if (this.has(value)){
			return false
		}
		this.items[value] = value
		return true
	}
	/*
	* 3. remove方法,移除指定屬性
	*/ 
	Set.prototype.remove = function(value){
		if (this.has(value) == false){
			return false
		}
		delete this.items[value]
		return true
	}
	/*
	* 4. clear方法,清除所有屬性
	*/ 
	Set.prototype.clear = function(){
		//使items重新指向一個空對象
		this.items = {}
	}
	/*
	* 5. size方法,獲取集合長度
	*/ 
	Set.prototype.size = function(){
		return Object.keys(this.items).length
	}
	/*
	* 6. values方法,獲取集合中的所有屬性值
	*/ 
	Set.prototype.values = function(){
		return Object.keys(this.items)
	}
	
	/*
	*
	* 集合與集合間的操作
	* this爲本集合 ,otherSet爲另一集合
	* 
	* 1. union方法,返回兩個集合的並集
	*/ 
	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
	}
	/*
	* 2. intersection方法,返回兩個集合的交集 
	*/ 
	Set.prototype.intersection = function(otherSet){
		//創建交集對象
		let intersection = new Set()
		//獲取本集合的所有元素
		let values = this.values()
		//遍歷本集合所有元素,判斷是否存在另一集合中,若存在則添加到intersection對象中
		for (let i = 0; i < this.size(); i++){
			if (otherSet.has(values[i])){
				intersection.add(values[i])
			}
		}
		return intersection
	}
	/*
	* 3. difference方法,返回兩個集合的差集(元素存在於本集合中,而不存在於另一集合中)
	*/ 
	Set.prototype.difference = function(otherSet){
		//創建差集對象
		let difference = new Set()
		let values = this.values()
		//遍歷本集合所有元素,判斷是否存在另一集合中,若不存在則添加到difference對象中
		for (let i = 0; i< this.size(); i++){
			if (otherSet.has(values[i]) == false){
				difference.add(values[i])
			}
		}
		return difference
	}
	/*
	* 4. isSubset方法,判斷本集合是否爲另一集合的子集
	*/ 
	Set.prototype.isSubset = function(otherSet){
		//如果本集合長度大於另一集合長度,則本集合必然不是另一集合的子集,返回false
		if (this.size() > otherSet.size()){
			return false
		}
		
		let values = this.values()
		for (let i =0; i < this.size(); i++){
			//一旦本集合中某個元素不存在於另一集合中,則返回false
			if (otherSet.has(values[i]) == false){
				return false
			}
		}
		//遍歷完成說明本集合所有元素都存在於另一集合,屬於另一集合的子集,返回true
		return true
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章