You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.3 KiB

4 years ago
  1. "use strict";
  2. /**
  3. * intersect creates Set containing the intersection of elements between all sets
  4. * @param {Set[]} sets an array of sets being checked for shared elements
  5. * @returns {Set<TODO>} returns a new Set containing the intersecting items
  6. */
  7. const intersect = sets => {
  8. if (sets.length === 0) return new Set();
  9. if (sets.length === 1) return new Set(sets[0]);
  10. let minSize = Infinity;
  11. let minIndex = -1;
  12. for (let i = 0; i < sets.length; i++) {
  13. const size = sets[i].size;
  14. if (size < minSize) {
  15. minIndex = i;
  16. minSize = size;
  17. }
  18. }
  19. const current = new Set(sets[minIndex]);
  20. for (let i = 0; i < sets.length; i++) {
  21. if (i === minIndex) continue;
  22. const set = sets[i];
  23. for (const item of current) {
  24. if (!set.has(item)) {
  25. current.delete(item);
  26. }
  27. }
  28. }
  29. return current;
  30. };
  31. /**
  32. * Checks if a set is the subset of another set
  33. * @param {Set<TODO>} bigSet a Set which contains the original elements to compare against
  34. * @param {Set<TODO>} smallSet the set whos elements might be contained inside of bigSet
  35. * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet
  36. */
  37. const isSubset = (bigSet, smallSet) => {
  38. if (bigSet.size < smallSet.size) return false;
  39. for (const item of smallSet) {
  40. if (!bigSet.has(item)) return false;
  41. }
  42. return true;
  43. };
  44. exports.intersect = intersect;
  45. exports.isSubset = isSubset;