stable-sort-domain.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. if (a.length !== b.length) {
  12. const r = a.length - b.length;
  13. if (r > 0) {
  14. return 1;
  15. }
  16. if (r < 0) {
  17. return -1;
  18. }
  19. return 0;
  20. }
  21. for (let i = 0; i < a.length; i++) {
  22. if (b[i] == null) {
  23. return 1;
  24. }
  25. if (a[i] < b[i]) {
  26. return -1;
  27. }
  28. if (a[i] > b[i]) {
  29. return 1;
  30. }
  31. }
  32. return 0;
  33. };
  34. const createDomainSorter = (gorhill: PublicSuffixList | null = null) => {
  35. if (gorhill) {
  36. const getDomain = createCachedGorhillGetDomain(gorhill);
  37. return (a: string, b: string) => {
  38. if (a === b) return 0;
  39. const aDomain = getDomain(a);
  40. const bDomain = getDomain(b);
  41. const resultDomain = compare(aDomain, bDomain);
  42. return resultDomain !== 0 ? resultDomain : compare(a, b);
  43. };
  44. }
  45. const tldts = require('./cached-tld-parse');
  46. return (a: string, b: string) => {
  47. if (a === b) return 0;
  48. const aDomain = tldts.parse(a).domain;
  49. const bDomain = tldts.parse(b).domain;
  50. const resultDomain = compare(aDomain, bDomain);
  51. return resultDomain !== 0 ? resultDomain : compare(a, b);
  52. };
  53. };
  54. export default createDomainSorter();
  55. export { createDomainSorter };