《学习javascript数据结构与算法》——第六章:集合

集合无序,元素唯一,以[值,值]的形式存储元素

创建集合

function Set() {
	var items = {};

	/*判断值是否在集合中*/
	this.has = function(value) {
		return value in items;
	};
	/*this.has = function(value) {		//方法2
		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.sizeLegacy = function() {
		var count = 0;
		for (var prop in items) {	//遍历属性(包含object类继承的)
			if (items.hasOwnProperty(prop)) {	//筛选出自己的属性
				count++;
			}
			return count;
		}
	};
	/*IE9+,其他浏览器可以,ECMAScript5*/
	this.size = function() {		//Object类的内建函数keys方法,返回一个包含给定对象所有属性的数组
		return Object.keys(items).length;
	};
	/*IE9+,其他浏览器可以,ECMAScript5*/
	this.values = function() {
		return Object.keys(items);
	};

	/*返回一个包含集合中所有值的数组*/
	this.valuesLegacy = function() {
		var keys = [];
		for (var key in items) {
			keys.push(key);
		}
		return keys;
	};
}

集合的操作

并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合

this.union = function(otherSet) {
	var unoinSet = new Set();
	var values = this.values();
	for (var i = 0; i < values.length; i++) {
		unoinSet.add(values[i]);
	}
	values = otherSet.values();
	for (var j = 0; j < values.length; j++) {
		unoinSet.add(values[j]); 
	}
	return unoinSet;
};
  • 首先创建一个新的集合,代表两个集合的并集
  • 获取第一个集合的所有值,遍历并添加到代表并集的集合中
  • 同样操作第二个集合
  • 返回结果

使用如下:

var setA = new Set();
setA.add(1);
setA.add(2);
setA.add(3);

var setB = new Set();
setB.add(3);
setB.add(4);
setB.add(5);
setB.add(6);

var unoinAB = setA.union(setB);
console.log(unoinAB.values());	// ["1", "2", "3", "4", "5", "6"]

交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合

this.intersection = function(otherSet) {
	var intersectionSet = new Set();
	var values = this.values();
	for (var i = 0; i < values.length; i++) {
		if (otherSet.has(values)) {
			intersectionSet.add(values[i]);
		}
	}
	return intersectionSet;
};
  • 首先创建一个新的集合,代表两个集合的交集
  • 获取第一个集合的所有值,并验证他们是否也是第二个集合的值
  • 如果是,才添加到新集合中
  • 返回结果

差集:对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集合的元素的新集合

this.difference = function(otherSet) {
	var differenceSet = new Set();
	var values = this.values();
	for (var 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 {
		var values = this.values();
		for (var i = 0; i < values.length; i++) {
			if (!otherSet.has(values[i])) {
				return false;
			}
		}
		return true;
	}
};
posted @ 2016-03-29 09:39  u14e  阅读(167)  评论(0编辑  收藏  举报