how to check if two sets are disjoint in typescript

To check if two sets are disjoint in typescript, one way is to check if their intersection is an empty set. We can do this by comparing the size of the intersection set to 0.

Here's an example implementation:

index.ts
function areSetsDisjoint<T>(set1: Set<T>, set2: Set<T>): boolean {
  // Get the intersection of the two sets
  const intersection = new Set([...set1].filter(x => set2.has(x)));
  
  // Check if intersection is an empty set
  return intersection.size === 0;
}
259 chars
8 lines

Explanation:

  • The function areSetsDisjoint takes in two sets of type T.
  • We create a new set called intersection by filtering out the elements in set1 that are not in set2.
  • We then check if the intersection set is empty by comparing its size to 0. If it is empty, the sets are disjoint and the function returns true. Otherwise, it returns false.

We can use this function like this:

index.ts
const set1 = new Set([1, 2, 3]);
const set2 = new Set([4, 5, 6]);
const set3 = new Set([2, 3, 4]);

console.log(areSetsDisjoint(set1, set2)); // true
console.log(areSetsDisjoint(set1, set3)); // false
201 chars
7 lines

gistlibby LogSnag