// 集合(不允许重复)es6提出了Set数据结构,也就是我们的集合
//这里我们通过对象来模拟集合,适用对象而不使用数组的原因是因为对象不允许有重复的属性
//是将集合中的值作为对象的键来定义
function Set(){
this.items = {};
//判断集合中有没有某一个值
this.has = function(val){
return this.items.hasOwnProperty(val);
}
//给集合中添加元素
this.add = function(val){
if(!this.has(val)){
this.items[val] = val;
return true;
}else{
return false;
}
}
//删除集合中某一个元素
this.remove = function(val){
if(this.has(val)){
delete this.items[val];
return true;
}else{
return false;
}
}
//清空集合
this.clear = function(){
this.items = {};
}
//统计集合中的元素个数
//方法一
// this.size = function () {
// return Object.keys(this.items).length;
// }
//方法二
this.size = function(){
var count = 0;
for(var prop in this.items){
if(this.has(prop)){
count++;
}
}
return count;
}
//返回集合中所有的元素
//方法一
// this.values = function(){
// return Object.keys(this.items);
// }
//方法二
this.values = function(){
var values = [];
for(var prop in this.items){
if(this.has(prop)){
values.push(prop);
}
}
return values;
}
//集合操作
//并集
this.union = function(set) {
var res = new Set();
var values = this.values();
for(var i=0;i<values.length;i++){
res.add(values[i]);
}
values = set.values();
for(var i=0;i<values.length;i++){
res.add(values[i]);
}
return res;
}
//交集
this.intersection = function(set){
var res = new Set();
var values = this.values();
for(var i=0;i<values.length;i++){
if(set.has(values[i])){
res.add(values[i]);
}
}
return res;
}
//差集
this.diffsection = function(set){
var res = new Set();
var values = this.values();
for(var i=0;i<values.length;i++){
if(!set.has(values[i])){
res.add(values[i]);
}
}
return res;
}
//子集
this.subset = function(set){
if(this.size() !== set.size()){
return false;
}
var values = this.values();
for(var i=0;i<values.length;i++){
if(!set.has(values[i])){
return false;
}
}
return true;
}
}
var s1 = new Set();
s1.add(1);
s1.add(2);
s1.add(3);
var s2 = new Set();
s2.add(4);
s2.add(5);
s2.add(6);
var res1 = s1.union(s2);
var res2 = s1.intersection(s2);
var res3 = s1.diffsection(s2);
console.log(res1.values());
console.log(res2.values());
console.log(res3.values());