partial_ordering.ts 589 B

1234567891011121314151617181920
  1. export function visitPartialOrdering<T>(elements: T[], smallerThan: (T) => T[], visitCallback: (T) => void) {
  2. const visitable = new Set(elements);
  3. const remaining = new Set(elements);
  4. while (remaining.size > 0) {
  5. let found = false;
  6. for (const elem of remaining) {
  7. if (smallerThan(elem).every(e => !visitable.has(e) || !remaining.has(e))) {
  8. visitCallback(elem);
  9. remaining.delete(elem);
  10. found = true;
  11. break;
  12. }
  13. }
  14. if (!found) {
  15. throw new Error("Could not find a smallest element - not a partial ordering?");
  16. }
  17. }
  18. }