集合: 无序不重复
/*
Set
集合:不重复并且无序
*/
function Set() {
var items = {};
/*集合中添加一个元素*/
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.has = function (value) {
return items.hasOwnProperty(value);
// return value in items;
}
/*清空集合*/
this.clear = function () {
items = {};
}
/*集合的大小*/
this.size = function () {
var cnt = 0;
for(var name in items) {
if(this.has(name)) {
cnt++
}
}
return cnt;
}
/*返回一个包含集合中所有元素的数组*/
this.values = function () {
var arr = [];
for(var name in items) {
if(this.has(name)) {
arr.push(items[name]);
}
}
return arr;
}
this.print = function () {
console.log(this.values());
}
/*并集*/
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) {
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 other_values = other_set.values();
var flag = true;
for(var i=0; i<other_values.length; ++i) {
if(!this.has(other_values[i])) {
return false;
}
}
return true;
}
}
/*测试函数*/
function test(arr) {
var set = new Set();
for(var i=0; i<arr.length; ++i) {
set.add(arr[i]);
}
return set;
}
var arr_a = [1, 2, 2, 3, 4];
var set_a = test(arr_a);
console.log(set_a.values());
var arr_b = [1, 3, 5, 9];
var set_b = test(arr_b);
console.log(set_b.values());
var arr_c = [1, 3, 4];
var set_c = test(arr_c);
console.log(set_c.values());
set_a.union(set_b).print();
set_a.intersection(set_b).print();
set_a.difference(set_b).print();
console.log(set_a.isSubset(set_c));
console.log(set_b.isSubset(set_c));