集合
- 集合通常是由一组无序的,不能重复的元素组成
- 特殊的数组
- 元素没有顺序,也不能重复
- 不能通过下标值进行访问,不能重复意味着相同的对象在集合中只会存在一份
class Set {
constructor() {
this.items = {}
}
/* 1. 添加新元素 */
add(value) {
// 1. 判断是否已经存在该元素
if (this.has(value)) return false
// 2. 将该元素添加到集合中
this.items[value] = value
return true
}
/* 2. 移出某个值 */
remove(value) {
// 1. 判断是否包含该元素
if (!this.has(value)) return false
// 2. 将该元素从集合中删除
delete this.items[value]
return true
}
/* 3. 检测某个值 */
has(value) {
return this.items.hasOwnProperty(value)
}
/* 4. 移除所有项 */
clear() {
this.items = {}
}
/* 5. 返回集合中元素的数量 */
size() {
return Object.keys(this.items).length
}
/* 6. 返回一个包含集合中所有值的数组 */
values() {
return Object.keys(this.items)
}
}
集合间的操作
并集(所有元素)
union (otherSet) {
/*
this: 集合对象A;
otherSet:集合对象B
*/
// 1. 创建新的集合
var unionSet = new Set()
// 2. 将A集合中的所有元素放入新集合中
var values = this.values()
for (let i = 0; i < values.length; i++) {
unionSet.add(values[i])
}
// 3. 取出B集合中的元素,判断是否需要添加到新集合中
values = otherSet.values()
for (let i = 0; i < values.length; i++) {
unionSet.add(values[i])
}
// 4. 返回新数组
return unionSet
}
交集(共有元素)
intersection (otherSet) {
/* this:集合对象A;otherSet:集合对象B */
// 1. 创建新的集合
var intersectionSet = new Set()
// 2. 将A集合中的所有元素放入新集合中
var values = this.values()
for (let i = 0; i < values.length; i++) {
var item = values[i]
if (otherSet.has(item)) {
intersectionSet.add(item)
}
}
// 3. 返回新数组
return intersectionSet
}
差集(A-B)
difference (otherSet) {
/* this:集合对象A;otherSet:集合对象B */
// 1. 创建新的集合
var differenceSet = new Set()
// 2. 添加A中的元素到新集合
var values = this.values()
for (let i = 0; i < values.length; i++) {
var item = values[i]
if (!otherSet.has(item)) {
differenceSet.add(item)
}
}
// 3. 返回新集合
return differenceSet
}
子集(A 包含 B)
subset (otherSet) {
/* this:集合对象A;otherSet:集合对象B */
// 1. 判断A中的元素是否是B中的元素
var values = this.values()
for (let i = 0; i < values.length; i++) {
var item = values[i]
if (!otherSet.has(item)) {
return false
}
}
// 2. 返回子集
return true
}