对两组数据(Set集合)进行并联
我们将在两个数据集上执行联合。我们将在我们的Set数据结构上创建一个名为union的方法。这个方法应该接受另一个Set作为参数,并返回这两个集合的并集,排除任何重复的值。
例如,如果setA = ['a', 'b', 'c'] and setB = ['a', 'b', 'd', 'e'],那么setA和setB的联合就是:setA.union(setB) = ['a', 'b', 'c', 'd', 'e']。
对两组数据进行交集
我们将对两组数据进行交集。我们将在Set数据结构上创建一个名为intersection的方法。集合的交集表示两个或更多集合的所有共同值。这个方法应该接受另一个Set作为参数,并返回这两个集合的交集。
例如,如果setA = ['a', 'b', 'c'] and setB = ['a', 'b', 'd', 'e'] ,那么setA和setB的交集是:setA.intersection(setB) = ['a', 'b']。
对两组数据进行差集
我们将对两组数据进行差异处理。我们将在我们的Set数据结构上创建一个方法,叫做difference。集合的差异应该比较两个集合,并返回第一个集合中存在而第二个集合中不存在的项目。这个方法应该接受另一个Set作为参数,并返回这两个集合的差值。
例如,如果setA = ['a', 'b', 'c'] and setB = ['a', 'b', 'd', 'e'], 那么setA和setB的差异是:setA.difference(setB) = ['c']。
对两组数据进行子集检验
在这个练习中,我们将对两组数据进行子集检验。我们将在Set数据结构上创建一个名为isSubsetOf的方法。这个方法将比较第一个集合和第二个集合,如果第一个集合完全包含在第二个集合中,它将返回true。
例如,如果setA = ['a', 'b'] and setB = ['a', 'b', 'c', 'd'], 那么setA是setB的一个子集,所以setA.isSubsetOf(setB)应该返回true。
class Set {
constructor() {
this.dictionary = {};
this.length = 0;
}
has(element) {
return this.dictionary[element] !== undefined;
}
values() {
return Object.keys(this.dictionary);
}
add(element) {
if (!this.has(element)) {
this.dictionary[element] = true;
this.length++;
return true;
}
return false;
}
remove(element) {
if (this.has(element)) {
delete this.dictionary[element];
this.length--;
return true;
}
return false;
}
size() {
return this.length;
}
union(set) {
const newSet = new Set();
this.values().forEach(value => {
newSet.add(value);
})
set.values().forEach(value => {
newSet.add(value);
})
return newSet;
}
//交集
intersection(set) {
const newSet = new Set();
this.values().forEach(value => {
if (set.values().includes(value))
newSet.add(value);
})
return newSet;
}
difference(set) {
const newSet = new Set();
this.values().forEach(value => {
if (!set.values().includes(value))
newSet.add(value);
})
return newSet;
}
}