set.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. /** Test if set a contains all elements of set b. */
  8. export function isSuperset<T>(setA: Set<T>, setB: Set<T>) {
  9. for (const elm of Array.from(setB)) {
  10. if (!setA.has(elm)) return false;
  11. }
  12. return true;
  13. }
  14. /** Create set containing elements of both set a and set b. */
  15. export function union<T>(setA: Set<T>, setB: Set<T>): Set<T> {
  16. const union = new Set(setA);
  17. for (const elem of Array.from(setB)) union.add(elem);
  18. return union;
  19. }
  20. export function unionMany<T>(sets: Set<T>[]) {
  21. if (sets.length === 0) return new Set<T>();
  22. if (sets.length === 1) return sets[0];
  23. const union = new Set(sets[0]);
  24. for (let i = 1; i < sets.length; i++) {
  25. for (const elem of Array.from(sets[i])) union.add(elem);
  26. }
  27. return union;
  28. }
  29. export function unionManyArrays<T>(arrays: T[][]) {
  30. if (arrays.length === 0) return new Set<T>();
  31. const union = new Set(arrays[0]);
  32. for (let i = 1; i < arrays.length; i++) {
  33. for (const elem of arrays[i]) union.add(elem);
  34. }
  35. return union;
  36. }
  37. /** Create set containing elements of set a that are also in set b. */
  38. export function intersection<T>(setA: Set<T>, setB: Set<T>): Set<T> {
  39. const intersection = new Set();
  40. for (const elem of Array.from(setB)) {
  41. if (setA.has(elem)) intersection.add(elem);
  42. }
  43. return intersection;
  44. }
  45. /** Create set containing elements of set a that are not in set b. */
  46. export function difference<T>(setA: Set<T>, setB: Set<T>): Set<T> {
  47. const difference = new Set(setA);
  48. for (const elem of Array.from(setB)) difference.delete(elem);
  49. return difference;
  50. }