stable-sort-domain.ts 940 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import * as tldts from 'tldts';
  2. import { sort } from './timsort';
  3. export const compare = (a: string, b: string) => {
  4. if (a === b) return 0;
  5. const aLen = a.length;
  6. const r = aLen - b.length;
  7. if (r !== 0) return r;
  8. return a.localeCompare(b);
  9. };
  10. const tldtsOpt = { allowPrivateDomains: false, detectIp: false, validateHostname: false };
  11. export const sortDomains = (inputs: string[]) => {
  12. const domains = inputs.reduce<Map<string, string>>((domains, cur) => {
  13. if (!domains.has(cur)) {
  14. const topD = tldts.getDomain(cur, tldtsOpt);
  15. domains.set(cur, topD ?? cur);
  16. };
  17. return domains;
  18. }, new Map());
  19. const sorter = (a: string, b: string) => {
  20. if (a === b) return 0;
  21. const $a = domains.get(a)!;
  22. const $b = domains.get(b)!;
  23. if (a === $a && b === $b) {
  24. return compare(a, b);
  25. }
  26. return $a.localeCompare($b) || compare(a, b);
  27. };
  28. sort(inputs, sorter);
  29. return inputs;
  30. };