集合是由一组无序且唯一(即不能重复)的项组成的。类似于一种特殊的数组,因为无序所以不能通过索引进行访问,不能重复意味着相同的元素在听一个集合里面是只能存在一份。
封装一个集合类
在集合内部是不需要再次进行内部类的。
function Set(){
// 属性
this.items = {}
// 方法
}
常见的方法
add(value):向集合添加一个新的项。
remove(value):从集合移除一个值。
has(value):如果值在集合中,返回true,否则返回false。
clear():移除集合中的所有项。
size():返回集合所包含元素的数量。与数组的length属性类似。
values():返回一个包含集合中所有值的数组。
(1)has方法实现
function Set(){
// 属性
this.items = {}
Set.prototype.has=(value)=>{
return this.items.hasOwnProperty(value)
}
}
(2)add方法实现
Set.prototype.add=(value)=>{
// 在添加之前先进行判断当前集合中是否已经存在当前元素
if(this.has(value)) return false
// 对象可以通过这种方式来设置键值对
this.items[value] = value
return true
}
(3)remove方法实现
Set.prototype.remove=(value)=>{
if(this.has(value)){
delete this.items[value]
return true
}else{
return false
}
}
(4)remove方法实现
Set.prototype.clear = ()=>{
return this.items = {}
}
(4)size方法实现
Set.prototype.size=()=>{
// Object.keys()一个表示给定对象的所有可枚举属性的字符串数组。
return Object.keys(this.items).length
}
(4)values 方法实现
// 获取集合中所有的值
Set.prototype.values = function(){
return Object.keys(this.items)
}
集合之间的操作
并集:对于给定的两个集合,返回一个包含两个集合中所有元素的新集合。
交集:对于给定的两个集合,返回一个包含两个集合中共有元素的新集合。
差集:对于给定的两个集合,返回一个包含所有存在于第一个集合且不存在于第二个集
合的元素的新集合。
子集:验证一个给定集合是否是另一集合的子集。
(1)并集的实现
// 并集
Set.prototype.union = function(otherSet){
var unionSet = new Set();
var values = this.values();
for (var i=0; i<values.length; i++){
unionSet.add(values[i]);
}
values = otherSet.values();
for (var i=0; i<values.length; i++){
unionSet.add(values[i]);
}
return unionSet;
}
(2)交集的实现
Set.prototype.interSection = function(otherSet){
var intersection = new Set()
//
var values = this.values()
console.log(otherSet)
for(var i=0;i<values.length;i++){
if(otherSet.has(values[i])){
intersection.add(values[i])
}
}
return intersection
}
(3)差集的实现
(4)子集的实现
Set.prototype.subset=function(otherSet){
var values = this.values()
for(var i=0;i<values.length;i++){
var item = values[i]
if(!otherSet.has(item)){
return false
}
}
return true
}