集合的實現2--使用數組

上節我們使用了對象來實現集合類,這節我們使用數組來實現同樣的功能

/*
	使用數組來模擬集合
*/
function Set() {
	var items = [];

	this.add = function (value) {
		if(this.has(value)) {
			return false;
		}

		items.push(value);
		return true;
	}

	this.has = function (value) {
		if(items.indexOf(value) == -1) {
			return false;
		}

		return true;
	}

	this.remove = function (value) {
		if(this.has(value)) {
			var index = items.indexOf(value);
			items.splice(index, 1);
			return true;
		}

		return false;
	}

	this.clear = function () {
		items = [];
	}

	this.size = function () {
		return items.length;
	}

	this.values = function () {
		return items;
	}

	this.print = function () {
		console.log(items);
	}

	this.union = function (other_set) {
		var new_set = new Set();
		var values = this.values();
		for(var i=0; i<values.length; ++i) {
			new_set.add(values[i]);
		}

		values = other_set.values();
		for(var i=0; i<values.length; ++i) {
			if(!new_set.has(values[i])) {
				new_set.add(values[i]);
			}
		}

		return new_set;
	}

	this.intersection = function (other_set) {
		var new_set = new Set();
		var values = this.values();

		for(var i=0; i<values.length; ++i) {
			if(other_set.has(values[i])) {
				new_set.add(values[i]);
			}
		}

		return new_set;
	}

	this.difference = function (other_set) {
		var new_set = new Set();
		var values = this.values();

		for(var i=0; i<values.length; ++i) {
			if(!other_set.has(values[i])) {
				new_set.add(values[i]);
			}
		}

		return new_set;
	}

	this.isSubset = function (other_set) {
		var flag = true;
		var values = other_set.values();
		for(var i=0; i<values.length; ++i) {
			if(!this.has(values[i])) {
				return false;
			}
		}

		return true;
	}
}

function getSet(arr) {
	var set = new Set();
	for(var i=0; i<arr.length; ++i) {
		set.add(arr[i]);
	}

	return set;
}

var arr1 = [1, 1, 2, 2, 3, 2, 4]  
var set1 = getSet(arr1); // set : [1, 2, 3, 4];

var arr2 = [1, 4, 5, 4, 4, 6];
var set2 = getSet(arr2);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章