Introduction
In this lab, we will explore how to use the Set constructor and Array.prototype.every() method to determine if one iterable is a superset of another. The lab will walk you through the creation of a function that checks if the first iterable contains all the elements of the second iterable, excluding any duplicates. By the end of the lab, you will have a better understanding of how to work with sets in JavaScript.
Function to Check if One Set is a Superset of Another Set
To check if one set is a superset of another set, use the superSet() function. First, open the Terminal/SSH and type node to start practicing coding. Then, use the following steps:
- Create a new
Setobject from each iterable using theSetconstructor. - Use
Array.prototype.every()andSet.prototype.has()to check that each value in the second iterable is contained in the first one. - The function returns
trueif the first iterable is a superset of the second one, excluding duplicate values. Otherwise, it returnsfalse.
const superSet = (a, b) => {
const sA = new Set(a),
sB = new Set(b);
return [...sB].every((v) => sA.has(v));
};
Use superSet() with two sets as arguments to check if one set is a superset of another set.
superSet(new Set([1, 2, 3, 4]), new Set([1, 2])); // true
superSet(new Set([1, 2, 3, 4]), new Set([1, 5])); // false
Summary
Congratulations! You have completed the Superset of Iterable lab. You can practice more labs in LabEx to improve your skills.