stable-sort-domain.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if (gorhill) {
  43. /**
  44. * @param {string} input
  45. */
  46. const getDomain = require('./cached-tld-parse').createCachedGorhillGetDomain(gorhill);
  47. /**
  48. * @param {string} a
  49. * @param {string} b
  50. * @returns {0 | 1 | -1}
  51. */
  52. return (a, b) => {
  53. if (a === b) return 0;
  54. const aDomain = getDomain(a);
  55. const bDomain = getDomain(b);
  56. const resultDomain = compare(aDomain, bDomain);
  57. return resultDomain !== 0 ? resultDomain : compare(a, b);
  58. };
  59. }
  60. const tldts = require('./cached-tld-parse');
  61. /**
  62. * @param {string} a
  63. * @param {string} b
  64. * @returns {0 | 1 | -1}
  65. */
  66. return (a, b) => {
  67. if (a === b) return 0;
  68. const aDomain = tldts.parse(a).domain;
  69. const bDomain = tldts.parse(b).domain;
  70. const resultDomain = compare(aDomain, bDomain);
  71. return resultDomain !== 0 ? resultDomain : compare(a, b);
  72. };
  73. };
  74. module.exports = createDomainSorter();
  75. module.exports.createDomainSorter = createDomainSorter;