stable-sort-domain.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import type { PublicSuffixList } from '@gorhill/publicsuffixlist';
  2. import { createCachedGorhillGetDomain } from './cached-tld-parse';
  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 getDomain = createCachedGorhillGetDomain(gorhill);
  34. const domains = inputs.reduce<Map<string, string>>((acc, cur) => {
  35. if (!acc.has(cur)) acc.set(cur, getDomain(cur));
  36. return acc;
  37. }, new Map());
  38. const sorter = (a: string, b: string) => {
  39. if (a === b) return 0;
  40. const $a = domains.get(a)!;
  41. const $b = domains.get(b)!;
  42. // avoid compare same thing twice
  43. if (a === $a && b === $b) {
  44. return compare(a, b);
  45. }
  46. return compare($a, $b) || compare(a, b);
  47. };
  48. return inputs.sort(sorter);
  49. };