set.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. // TODO remove Array.from workaround when targeting ES6
  7. export namespace SetUtils {
  8. /** Test if set a contains all elements of set b. */
  9. export function isSuperset<T>(setA: Set<T>, setB: Set<T>) {
  10. for (const elm of Array.from(setB)) {
  11. if (!setA.has(elm)) return false;
  12. }
  13. return true;
  14. }
  15. /** Create set containing elements of both set a and set b. */
  16. export function union<T>(setA: Set<T>, setB: Set<T>): Set<T> {
  17. const union = new Set(setA);
  18. for (const elem of Array.from(setB)) union.add(elem);
  19. return union;
  20. }
  21. export function unionMany<T>(...sets: Set<T>[]) {
  22. if (sets.length === 0) return new Set<T>();
  23. if (sets.length === 1) return sets[0];
  24. const union = new Set(sets[0]);
  25. for (let i = 1; i < sets.length; i++) {
  26. for (const elem of Array.from(sets[i])) union.add(elem);
  27. }
  28. return union;
  29. }
  30. export function unionManyArrays<T>(arrays: T[][]) {
  31. if (arrays.length === 0) return new Set<T>();
  32. const union = new Set(arrays[0]);
  33. for (let i = 1; i < arrays.length; i++) {
  34. for (const elem of arrays[i]) union.add(elem);
  35. }
  36. return union;
  37. }
  38. /** Create set containing elements of set a that are also in set b. */
  39. export function intersection<T>(setA: Set<T>, setB: Set<T>): Set<T> {
  40. const intersection = new Set<T>();
  41. for (const elem of Array.from(setB)) {
  42. if (setA.has(elem)) intersection.add(elem);
  43. }
  44. return intersection;
  45. }
  46. /** Create set containing elements of set a that are not in set b. */
  47. export function difference<T>(setA: Set<T>, setB: Set<T>): Set<T> {
  48. const difference = new Set(setA);
  49. for (const elem of Array.from(setB)) difference.delete(elem);
  50. return difference;
  51. }
  52. /** Test if set a and b contain the same elements. */
  53. export function areEqual<T>(setA: Set<T>, setB: Set<T>) {
  54. if (setA.size !== setB.size) return false
  55. for (const elm of Array.from(setB)) {
  56. if (!setA.has(elm)) return false;
  57. }
  58. return true;
  59. }
  60. }