109 lines
2.4 KiB
JavaScript
109 lines
2.4 KiB
JavaScript
/**
|
|
* @author yutent<yutent.io@gmail.com>
|
|
* @date 2020/09/16 11:54:31
|
|
*/
|
|
|
|
if (!Set.prototype.union) {
|
|
// 类似 Array的concat, 合并2个集合, 返回1个新集合, 原集合不发生变化
|
|
Object.defineProperty(Set.prototype, 'union', {
|
|
value(other) {
|
|
let output = new Set([...this])
|
|
if (
|
|
other.size !== void 0 &&
|
|
other.has !== void 0 &&
|
|
other.keys !== void 0
|
|
) {
|
|
for (let it of other.keys()) {
|
|
output.add(it)
|
|
}
|
|
}
|
|
return output
|
|
}
|
|
})
|
|
|
|
// 同一批 API
|
|
// 返回不存在于另一个集合的所有元素集合
|
|
Object.defineProperty(Set.prototype, 'difference', {
|
|
value(other) {
|
|
let output = new Set()
|
|
for (let it of this) {
|
|
if (!other.has(it)) {
|
|
output.add(it)
|
|
}
|
|
}
|
|
return output
|
|
}
|
|
})
|
|
|
|
// 返回当前集合与给定集合中, 不同时存在的所有元素集合
|
|
Object.defineProperty(Set.prototype, 'symmetricDifference', {
|
|
value(other) {
|
|
let output = this.difference(other)
|
|
for (let it of other) {
|
|
if (!this.has(it)) {
|
|
output.add(it)
|
|
}
|
|
}
|
|
return output
|
|
}
|
|
})
|
|
|
|
// 返回共有的元素集合
|
|
Object.defineProperty(Set.prototype, 'intersection', {
|
|
value(other) {
|
|
let output = new Set()
|
|
|
|
for (let it of this) {
|
|
if (other.has(it)) {
|
|
output.add(it)
|
|
}
|
|
}
|
|
|
|
return output
|
|
}
|
|
})
|
|
|
|
// 判断当前集合是否为给定集合的子集
|
|
Object.defineProperty(Set.prototype, 'isSubsetOf', {
|
|
value(other) {
|
|
for (let it of this) {
|
|
if (!other.has(it)) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
})
|
|
|
|
// 判断当前集合是否为给定集合的子超集
|
|
Object.defineProperty(Set.prototype, 'isSupersetOf', {
|
|
value(other) {
|
|
for (let it of other) {
|
|
if (!this.has(it)) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
})
|
|
|
|
// 判断当前集合,是否与给定集合完全不重合
|
|
Object.defineProperty(Set.prototype, 'isDisjointFrom', {
|
|
value(other) {
|
|
for (let it of this) {
|
|
if (other.has(it)) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
})
|
|
}
|
|
|
|
// 判断2个集合是否一致(仅元素相同, 无关顺序)
|
|
Object.defineProperty(Set.prototype, 'equal', {
|
|
value(other) {
|
|
return this.size === other.size && this.isSubsetOf(other)
|
|
}
|
|
})
|