The Set object provides some methods that allow you to compose sets like you would with mathematical operations. These methods include
Method | Return type | Mathematical equivalent |
---|---|---|
A.difference(B) | Set | A \ B |
A.intersection(B) | Set | A ∩ B |
A.symmetricDifference(B) | Set | ( A \ B ) U ( B \ A ) |
A.union(B) | Set | A U B |
A.isDisjointFrom(B) | Boolean | A ∩ B = ∅ |
A.isSubsetOf(B) | Boolean | A ⊆ B |
A.isSupersetOf(B) | Boolean | A ⊇ B |
To make them more generalizable, these methods don't just accept Set objects, but anything that's set-like.
All set composition methods require this to be an actual Set instance, but their arguments just need to be set-like. A set-like object is an object that provides the following:
For example, Map objects are set-like because they also have size, has(), and keys(), so they behave just like sets of keys when used in set methods.
const a = new Set([1, 2, 3]);
const b = new Map([
[1, "one"],
[2, "two"],
[4, "four"],
]);
console.log(a.union(b)); // Set(4) {1, 2, 3, 4}
Arrays are not set-like because they don't have a has() method or the size property, and their keys() method produces indices instead of elements. WeakSet objects are also not set-like because they don't have a keys() method.