A set is a collection of any type of comparable data. Data in a set can occur only once.
Example;
{..., -3, -1, 1, 3, ...} is a set of odd numbers
Basic Set Implementations
new Set() - create a new set
Set.prototype.has() - returns true if element is present in Set object
Set.prototype.add() - adds a new item to set object
Set.prototype.delete() - removes specified item from set object
1.Union Algorithm
This is a set algorithm that compares two sets and returns a third set that contains all of the unique items in both sets.
function union(setA, setB) {
let result = new Set(setA); // new set containing items in setA
for (let elem of setB) {
// add items from setB to the new set
// an element can't be added twice
result.add(elem);
}
return result;
}
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);
console.log(union(setA, setB));
// >> Set { 1, 2, 3, 4, 5 }
2.Intersection Algorithm
Compares two sets and returns a third set that contains all of the matching members of both sets.
function intersection(setA, setB) {
let result = new Set(); // new empty set
for (let elem of setA) {
if (setB.has(elem)){ // if matching elements found
result.add(elem); // add to new set
}
}
return result;
}
let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);
console.log(intersection(setA, setB));
// >> Set { 2, 3 }
3.Set Difference Algorithm
Takes two sets, A and B, and return all the items of A that are not members of B.
function setDifference(setA, setB) {
let result = new Set(setA);
for (let item of setB) {
result.delete(item); // delete items in A that exist in B
}
return result;
}
let setA = new Set([2, 3, 4]);
let setB = new Set([3, 4, 5]);
console.log(setDifference(setA, setB));
// >> Set { 2 }
4.Symmetric Difference Algorithm
Takes two sets and returns a third set that contains all of the members of both sets that are not in the other
function symmetricDifference(setA, setB) {
let difference = new Set(setA);
for (let elem of setB) {
if (difference.has(elem)) {
difference.delete(elem); // if item in B exists in A, remove
} else {
difference.add(elem) // else add to new set
}
}
return difference;
}
let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);
console.log(symmetricDifference(setA, setB));
// >> Set { 1, 4 }
Symmetric Difference can also be described as the set difference of the intersection and union of the input sets
function symmetricDifference(setA, setB) {
let intersectionResult = intersection(setA, setB)
let unionResult = union(setA, setB);
return setDifference(unionResult, intersectionResult,)
}
let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);
console.log(symmetricDifference(setA, setB));
// >> Set { 1, 4 }
Top comments (0)