stable-sort-domain.ts 1.1 KB

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