SetHelpers.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /**
  7. * intersect creates Set containing the intersection of elements between all sets
  8. * @template T
  9. * @param {Set<T>[]} sets an array of sets being checked for shared elements
  10. * @returns {Set<T>} returns a new Set containing the intersecting items
  11. */
  12. const intersect = sets => {
  13. if (sets.length === 0) return new Set();
  14. if (sets.length === 1) return new Set(sets[0]);
  15. let minSize = Infinity;
  16. let minIndex = -1;
  17. for (let i = 0; i < sets.length; i++) {
  18. const size = sets[i].size;
  19. if (size < minSize) {
  20. minIndex = i;
  21. minSize = size;
  22. }
  23. }
  24. const current = new Set(sets[minIndex]);
  25. for (let i = 0; i < sets.length; i++) {
  26. if (i === minIndex) continue;
  27. const set = sets[i];
  28. for (const item of current) {
  29. if (!set.has(item)) {
  30. current.delete(item);
  31. }
  32. }
  33. }
  34. return current;
  35. };
  36. /**
  37. * Checks if a set is the subset of another set
  38. * @template T
  39. * @param {Set<T>} bigSet a Set which contains the original elements to compare against
  40. * @param {Set<T>} smallSet the set whose elements might be contained inside of bigSet
  41. * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet
  42. */
  43. const isSubset = (bigSet, smallSet) => {
  44. if (bigSet.size < smallSet.size) return false;
  45. for (const item of smallSet) {
  46. if (!bigSet.has(item)) return false;
  47. }
  48. return true;
  49. };
  50. /**
  51. * @template T
  52. * @param {Set<T>} set a set
  53. * @param {function(T): boolean} fn selector function
  54. * @returns {T | undefined} found item
  55. */
  56. const find = (set, fn) => {
  57. for (const item of set) {
  58. if (fn(item)) return item;
  59. }
  60. };
  61. /**
  62. * @template T
  63. * @param {Set<T>} set a set
  64. * @returns {T | undefined} first item
  65. */
  66. const first = set => {
  67. const entry = set.values().next();
  68. return entry.done ? undefined : entry.value;
  69. };
  70. /**
  71. * @template T
  72. * @param {Set<T>} a first
  73. * @param {Set<T>} b second
  74. * @returns {Set<T>} combined set, may be identical to a or b
  75. */
  76. const combine = (a, b) => {
  77. if (b.size === 0) return a;
  78. if (a.size === 0) return b;
  79. const set = new Set(a);
  80. for (const item of b) set.add(item);
  81. return set;
  82. };
  83. exports.intersect = intersect;
  84. exports.isSubset = isSubset;
  85. exports.find = find;
  86. exports.first = first;
  87. exports.combine = combine;