[ES2024] Perform Set Operations using JavaScript Set Methods

The "Set Methods" proposal introduces 7 new methods to JavaScript/ECMAScript:

  1. union(setB): Returns a new Set containing all elements from the original set and another set setB. This method effectively combines the members of two sets without duplication.

  2. intersection(setB): Returns a new Set containing all elements that are present in both the original set and set setB. This method identifies common elements between two sets.

  3. difference(setB): Returns a new Set containing all elements that are in the original set but not in set setB. It helps in identifying elements that are unique to the first set when compared to another set.

  4. symmetricDifference(setB): Returns a new Set containing all elements that are in either of the sets but not in their intersection. This method is useful for finding elements that are in either one set or the other, but not in both.

  5. isSubsetOf(setB): Returns a boolean indicating whether the original set is a subset of set setB. A set is a subset of another set if all elements of the former are contained in the latter.

  6. isSupersetOf(setB): Returns a boolean indicating whether the original set is a superset of set setB. A set is a superset of another set if it contains all elements of the latter set.

  7. isDisjointFrom(setB): Returns a boolean indicating whether the original set and set setB have no elements in common. If they have no common elements, the sets are considered disjoint.

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

// Using union to combine two sets
const unionSet = setA.union(setB);
console.log('Union of setA and setB:', [...unionSet]);

// Using intersection to find common elements
const intersectionSet = setA.intersection(setB);
console.log('Intersection of setA and setB:', [...intersectionSet]);

// Using difference to find elements in setA not in setB
const differenceSet = setA.difference(setB);
console.log('Difference of setA from setB:', [...differenceSet]);

// Using symmetricDifference to find elements in either set but not in both
const symmetricDifferenceSet = setA.symmetricDifference(setB);
console.log('Symmetric Difference between setA and setB:', [...symmetricDifferenceSet]);

// Checking if setA is a subset of setB
const isSubset = setA.isSubsetOf(setB);
console.log('Is setA a subset of setB?', isSubset);

// Checking if setA is a superset of setB
const isSuperset = setA.isSupersetOf(setB);
console.log('Is setA a superset of setB?', isSuperset);

// Checking if setA is disjoint from setB
const isDisjoint = setA.isDisjointFrom(setB);
console.log('Are setA and setB disjoint?', isDisjoint);

 

posted @ 2024-05-20 21:59  Zhentiw  阅读(5)  评论(0编辑  收藏  举报