In: Computer Science
1. Implement the union set function using the prototype.
2. Implement the intersection set function using the prototype.
3. Implement the set difference function using the prototype.
4. Implement the subset function using the prototype.
a)Union
Set.prototype.union = function(otherSet) {
var unionSet = new Set();
for (var elem of this) {
unionSet.add(elem);
}
for(var elem of otherSet)
unionSet.add(elem);
return unionSet;
}
var set1 = new Set([10, 20, 30, 40, 50]);
var set2 = new Set([40, 50, 60, 70, 80]);
var unionSet = set1.union(set2);
console.log(unionSet.values());
b) Intersection
Set.prototype.intersection = function(otherSet) {
var intersectionSet = new Set();
for(var elem of otherSet) {
if(this.has(elem))
intersectionSet.add(elem);
}
return intersectionSet;
}
var set1 = new Set([10, 20, 30, 40, 50]);
var set2 = new Set([40, 50, 60, 70, 80]);
var intersectionSet = set1.intersection(set2);
console.log(intersectionSet.values());
c)Diffrence
Set.prototype.difference = function(otherSet) {
var differenceSet = new Set();
for(var elem of this) {
if(!otherSet.has(elem))
differenceSet.add(elem);
}
return differenceSet;
}
var set1 = new Set([10, 20, 30, 40, 50]);
var set2 = new Set([40, 50, 60, 70, 80]);
var differenceSet = set1.difference(set2);
console.log(differenceSet);
d)subset
Set.prototype.subSet = function(otherSet) {
if(this.size > otherSet.size)
return false;
else{
for(var elem of this) {
if(!otherSet.has(elem))
return false;
}
return true;
}
}
var setA = new Set([10, 20, 30]);
var setB = new Set([50, 60, 10, 20, 30, 40]);
var setC = new Set([10, 30, 40, 50]);
console.log(setA.subSet(setB));
console.log(setA.subSet(setC));
console.log(setC.subSet(setB));
Happy Coding.
PLEASE GIVE A THUMBSUP IF IT WAS HELPFUL AND LEAVE A COMMENT FOR ANY QUERY.
THANKS.