set.ts 721 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Performs a shallow comparison of two sets with the same item type.
  3. */
  4. export function equal<T>(a: Set<T>, b: Set<T>): boolean {
  5. if (a.size !== b.size) {
  6. return false;
  7. }
  8. const it = a.values();
  9. while (true) {
  10. const { value, done } = it.next();
  11. if (done) {
  12. return true;
  13. }
  14. if (!b.has(value)) {
  15. return false;
  16. }
  17. }
  18. }
  19. /**
  20. * Returns a new set with items in both sets using shallow comparison.
  21. */
  22. export function intersect<T>(a: Set<T>, b: Set<T>): Set<T> {
  23. const result = new Set<T>();
  24. const it = b.values();
  25. while (true) {
  26. const { value, done } = it.next();
  27. if (done) {
  28. return result;
  29. }
  30. if (a.has(value)) {
  31. result.add(value);
  32. }
  33. }
  34. }