stable-sort-domain.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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<Record<string, string>>((acc, cur) => {
  35. acc[cur] ||= getDomain(cur);
  36. return acc;
  37. }, {});
  38. const sorter = (a: string, b: string) => {
  39. if (a === b) return 0;
  40. const aDomain = domains[a];
  41. const bDomain = domains[b];
  42. return compare(aDomain, bDomain) || compare(a, b);
  43. };
  44. return inputs.sort(sorter);
  45. };