We can compare ES6 sets for equality by looping through its contents and check if any element in one set is missing in the other and check that their sizes are equal.
For instance, we can write:
const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 2]);
const eqSet = (as, bs) => {
if (as.size !== bs.size) {
return false;
}
for (const a of as) {
if (!bs.has(a)) {
return false;
}
}
return true;
}
console.log(eqSet(a, b));
We created the a
and b
sets which we want to compare.
Then we create the eqSet
function with the as
and bs
parameters which are sets.
In the function, we compare is as
and bs
have different sizes. If they don’t then we return false
.
Then if they have the same size, we loop through the as
set with the for-of loop.
In the loop body, we check if bs
is missing any items in as
.
If something is missing, we return false
.
If the loop is finished then we return true
since both sets have the same size and has all the same elements.
Therefore, the console log should log true
.