stable-sort-domain.ts 1.1 KB

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