stable-sort-domain.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // @ts-check
  2. /**
  3. * @param {string | null} a
  4. * @param {string | null} b
  5. * @returns {0 | 1 | -1}
  6. */
  7. const compare = (a, b) => {
  8. if (a === b) return 0;
  9. if (b == null) {
  10. return 1;
  11. }
  12. if (a == null) {
  13. return -1;
  14. }
  15. if (a.length !== b.length) {
  16. const r = a.length - b.length;
  17. if (r > 0) {
  18. return 1;
  19. }
  20. if (r < 0) {
  21. return -1;
  22. }
  23. return 0;
  24. }
  25. for (let i = 0; i < a.length; i++) {
  26. if (b[i] == null) {
  27. return 1;
  28. }
  29. if (a[i] < b[i]) {
  30. return -1;
  31. }
  32. if (a[i] > b[i]) {
  33. return 1;
  34. }
  35. }
  36. return 0;
  37. };
  38. /**
  39. * @param {import('gorhill-publicsuffixlist').default | null} [gorhill]
  40. */
  41. const createDomainSorter = (gorhill = null) => {
  42. const cached = require('./cached-tld-parse');
  43. if (gorhill) {
  44. /**
  45. * @param {string} input
  46. */
  47. const getDomain = cached.createCachedGorhillGetDomain(gorhill);
  48. /**
  49. * @param {string} a
  50. * @param {string} b
  51. * @returns {0 | 1 | -1}
  52. */
  53. return (a, b) => {
  54. if (a === b) return 0;
  55. const aDomain = getDomain(a);
  56. const bDomain = getDomain(b);
  57. const resultDomain = compare(aDomain, bDomain);
  58. return resultDomain !== 0 ? resultDomain : compare(a, b);
  59. };
  60. }
  61. const tldts = cached;
  62. /**
  63. * @param {string} a
  64. * @param {string} b
  65. * @returns {0 | 1 | -1}
  66. */
  67. return (a, b) => {
  68. if (a === b) return 0;
  69. const aDomain = tldts.parse(a).domain;
  70. const bDomain = tldts.parse(b).domain;
  71. const resultDomain = compare(aDomain, bDomain);
  72. return resultDomain !== 0 ? resultDomain : compare(a, b);
  73. };
  74. };
  75. module.exports = createDomainSorter();
  76. module.exports.createDomainSorter = createDomainSorter;