javascript数据结构(五)集合

集合

function Set() {
	let items = {};
	this.has = function(value) {
		// return value in items;
		// 或者
		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 () {
		// return object.keys(items).length;
		let count = 0;
		for(let key in items) {
			if (items.hasOwnProperty(key)) 
				++count;
		}
		return count;
	};
	this.values = function(){
		let value = [];
		for (var i = 0,keys = Object.keys(items); i < keys.length; i++) {
			value.push(items[keys[i]]);
		}
		return value;
	};
	// 可以在任何浏览器中运行
	this.valuesLegacy = function() {
		let values = [];
		for(let key in items) {
			if (items.push(items[key])) {
				value.push(items[key]);
			}
		}
		return values;
	};
	// 实现并集的方法
	this.union = function(otherSet) {
		let unionSet = new Set();
		let values = this.values();
		for (var i = 0; i < value.length; i++) {
			unionSet.add(value[i]);
		}

		value  = otherSet.values();
		for (var i = 0; i < value.length; i++) {
			unionSet.add(value[i]);
		}

		return unionSet;
	};
	// 实现交集的方法
	this.insertsection = function(otherSet) {
		let insertsectionSet = new Set();
		let value = this.values();
		for (var i = 0; i < value.length; i++) {
			if(otherSet.has(value))
				insertsectionSet.add(value);
		}
		return insertsectionSet;
	};
	this.difference = function(otherSet) {
		let differenceSet = new Set();
		let values = this.values();
		for (var i = 0; i < values.length; i++) {
			if(!this.insertsection(otherSet))
				differenceSet.add(values[i]);
		}
		return differenceSet;
	};
	this.subset = function(otherSet) {
		if (this.size() > otherSet.size()) {
			return false;
		} else {
			let values = this.values();
			for (var i = 0; i < values.length; i++) {
				 if(!otherSet.has(values[i])){
				 	return false;
				 }
			}
			return true;
		}
	};
	
}

猜你喜欢

转载自blog.csdn.net/qq_35532442/article/details/81133875