Sub topic 2
Removing Elements with difference
This chapter assumes you know how to create a Set, that you have already seen union and intersection, and that you know these methods return a new Set without changing either input.
Removing Elements with difference
a.difference(b) returns a new Set with the elements of a that are not in b. The receiver matters. Unlike union and intersection, difference is not symmetric, so swapping the two sets changes the result.
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5]);
console.log([...a.difference(b)]); // [1, 2]
console.log([...b.difference(a)]); // [5]A common mistake is reading a.difference(b) as "what differs between a and b." It actually means "a minus b." If you need the elements that differ in both directions, use the next method.
Elements in Exactly One Set: symmetricDifference
a.symmetricDifference(b) returns the elements that belong to exactly one of the two sets. You get the same result as a.difference(b).union(b.difference(a)), but with a single call.
const a = new Set([1, 2, 3]);
const b = new Set([3, 4]);
console.log([...a.symmetricDifference(b)]); // [1, 2, 4]Comparing Sets: isSubsetOf, isSupersetOf, isDisjointFrom
The three predicate methods return a boolean and do not build a new Set:
| Method | True when |
|---|---|
| `a.isSubsetOf(b)` | every element of `a` is in `b` |
| `a.isSupersetOf(b)` | every element of `b` is in `a` |
| `a.isDisjointFrom(b)` | `a` and `b` share no elements |
const required = new Set(["read", "write"]);
const granted = new Set(["read", "write", "delete"]);
const banned = new Set(["admin"]);
console.log(required.isSubsetOf(granted)); // true
console.log(granted.isSupersetOf(required)); // true
console.log(granted.isDisjointFrom(banned)); // trueExercise
Given const a = new Set(["x", "y"]) and const b = new Set(["y", "z"]), what do [...b.difference(a)] and a.isDisjointFrom(b) return?
Show answer
[...b.difference(a)] returns ["z"], because only "z" is in b but not in a. a.isDisjointFrom(b) returns false, because both sets contain "y".
Exercise
Write one expression that checks whether a user's granted permissions include every permission in required.
Show answer
required.isSubsetOf(granted), or the equivalent granted.isSupersetOf(required).