stable-sort-domain.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import type { PublicSuffixList } from '@gorhill/publicsuffixlist';
  2. import { sort } from './timsort';
  3. 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) {
  8. return 1;
  9. }
  10. if (r < 0) {
  11. return -1;
  12. }
  13. for (let i = 0; i < aLen; i++) {
  14. // if (b[i] == null) {
  15. // return 1;
  16. // }
  17. if (a[i] < b[i]) {
  18. return -1;
  19. }
  20. if (a[i] > b[i]) {
  21. return 1;
  22. }
  23. }
  24. return 0;
  25. };
  26. export const sortDomains = (inputs: string[], gorhill: PublicSuffixList) => {
  27. const domains = inputs.reduce<Map<string, string | null>>((acc, cur) => {
  28. if (!acc.has(cur)) {
  29. const topD = gorhill.getDomain(cur[0] === '.' ? cur.slice(1) : cur);
  30. acc.set(cur, topD === cur ? null : topD);
  31. };
  32. return acc;
  33. }, new Map());
  34. const sorter = (a: string, b: string) => {
  35. if (a === b) return 0;
  36. const $a = domains.get(a);
  37. const $b = domains.get(b);
  38. if ($a == null || $b == null) {
  39. return compare(a, b);
  40. }
  41. return compare($a, $b) || compare(a, b);
  42. };
  43. sort(inputs, sorter);
  44. return inputs;
  45. };