stable-sort-domain.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. return compare(domains.get(a)!, domains.get(b)!) || compare(a, b);
  41. };
  42. return inputs.sort(sorter);
  43. };