集合的實現3--ES6的set類型

ES6也實現了Set類型。

ES6入門之set和map


我們看到

var set = new Set([1, 2, 2, 3, 3]);

console.log(set);


我們也可以稍微修改一下程序。使之可以接受參數。

看下面的註釋部分。由於使用的是函數表達式(對應的是函數聲明)。因此代碼得放在合理的位置

/*
	使用數組來模擬集合
*/
function Set(arr) {
	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;
	}

	/*添加一些Set初始化的代碼*/
	if(arr) {
		for(var i=0; i<arr.length; ++i) {
			this.add(arr[i])
		}
	}

	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;
	}
}

var set = new Set([1, 2, 2, 1, 3]);
set.print();




發佈了88 篇原創文章 · 獲贊 37 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章