集合数据结构的概念
集合常用的方法
集合间的操作
简单集合的代码实现
<script>
function Set() {
this.items = {}
Set.prototype.add = function(value) {
if (this.has(value)) {
return false;
}
this.items[value] = value;
return true;
}
Set.prototype.has = function(value) {
return this.items.hasOwnProperty(value);
}
Set.prototype.remove = function(value) {
if (!this.has(value)) {
return false;
}
delete this.items[value];
return true;
}
Set.prototype.clear = function() {
return this.items = {};
}
Set.prototype.values = function() {
return Object.keys(this.items);
}
Set.prototype.size = function() {
return Object.keys(this.items).length;
}
//集合并集操作
Set.prototype.union = function(otherSet) {
var unionSet = new Set();
var values = this.values();
for (var i = 0; i < values.length; i++) {
var item = values[i];
if (!otherSet.has(item)) {
unionSet.add(item);
}
}
values = otherSet.values()
for (var i = 0; i < values.length; i++) {
unionSet.add(values[i]);
}
return unionSet;
}
//集合交集操作
Set.prototype.intersection = function(otherSet) {
var intersection = new Set();
var values = this.values();
for (var i = 0; i < values.length; i++) {
var item = values[i];
if (otherSet.has(item)) {
intersection.add(item);
}
}
return intersection;
}
//集合差集操作
Set.prototype.difference = function(otherSet) {
var differenceSet = new Set();
var values = this.values();
for (var i = 0; i < values.length; i++) {
var item = values[i];
if (!otherSet.has(item)) {
differenceSet.add(item);
}
}
return differenceSet;
}
//集合子集操作
Set.prototype.subSet = function(otherSet) {
var values = this.values();
for (var i = 0; i < value.length; i++) {
var item = values[i];
if (!otherSet.has(item)) {
return false;
}
}
return true;
}
}
//测试代码
var setA = new Set();
var setB = new Set();
setA.add("aaa");
setA.add("bbb");
setA.add("ccc");
setB.add("ddd");
setB.add("eee");
setB.add("fff");
setB.add("aaa");
alert(setA.union(setB).values());
alert(setA.intersection(setB).values());
alert(setA.difference(setB).values());
// alert(set.add("aaa"));
// alert(set.add("bbb"));
// alert(set.add("ccc"));
// // set.clear();
// alert(set.remove("aaa"))
// alert(set.values())
// alert(set.size())
</script>
文章部分转载于coderwhy老师教学视频。