sort.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.isTraversal = void 0;
  4. var css_what_1 = require("css-what");
  5. var procedure = new Map([
  6. [css_what_1.SelectorType.Universal, 50],
  7. [css_what_1.SelectorType.Tag, 30],
  8. [css_what_1.SelectorType.Attribute, 1],
  9. [css_what_1.SelectorType.Pseudo, 0],
  10. ]);
  11. function isTraversal(token) {
  12. return !procedure.has(token.type);
  13. }
  14. exports.isTraversal = isTraversal;
  15. var attributes = new Map([
  16. [css_what_1.AttributeAction.Exists, 10],
  17. [css_what_1.AttributeAction.Equals, 8],
  18. [css_what_1.AttributeAction.Not, 7],
  19. [css_what_1.AttributeAction.Start, 6],
  20. [css_what_1.AttributeAction.End, 6],
  21. [css_what_1.AttributeAction.Any, 5],
  22. ]);
  23. /**
  24. * Sort the parts of the passed selector,
  25. * as there is potential for optimization
  26. * (some types of selectors are faster than others)
  27. *
  28. * @param arr Selector to sort
  29. */
  30. function sortByProcedure(arr) {
  31. var procs = arr.map(getProcedure);
  32. for (var i = 1; i < arr.length; i++) {
  33. var procNew = procs[i];
  34. if (procNew < 0)
  35. continue;
  36. for (var j = i - 1; j >= 0 && procNew < procs[j]; j--) {
  37. var token = arr[j + 1];
  38. arr[j + 1] = arr[j];
  39. arr[j] = token;
  40. procs[j + 1] = procs[j];
  41. procs[j] = procNew;
  42. }
  43. }
  44. }
  45. exports.default = sortByProcedure;
  46. function getProcedure(token) {
  47. var _a, _b;
  48. var proc = (_a = procedure.get(token.type)) !== null && _a !== void 0 ? _a : -1;
  49. if (token.type === css_what_1.SelectorType.Attribute) {
  50. proc = (_b = attributes.get(token.action)) !== null && _b !== void 0 ? _b : 4;
  51. if (token.action === css_what_1.AttributeAction.Equals && token.name === "id") {
  52. // Prefer ID selectors (eg. #ID)
  53. proc = 9;
  54. }
  55. if (token.ignoreCase) {
  56. /*
  57. * IgnoreCase adds some overhead, prefer "normal" token
  58. * this is a binary operation, to ensure it's still an int
  59. */
  60. proc >>= 1;
  61. }
  62. }
  63. else if (token.type === css_what_1.SelectorType.Pseudo) {
  64. if (!token.data) {
  65. proc = 3;
  66. }
  67. else if (token.name === "has" || token.name === "contains") {
  68. proc = 0; // Expensive in any case
  69. }
  70. else if (Array.isArray(token.data)) {
  71. // Eg. :matches, :not
  72. proc = Math.min.apply(Math, token.data.map(function (d) { return Math.min.apply(Math, d.map(getProcedure)); }));
  73. // If we have traversals, try to avoid executing this selector
  74. if (proc < 0) {
  75. proc = 0;
  76. }
  77. }
  78. else {
  79. proc = 2;
  80. }
  81. }
  82. return proc;
  83. }
  84. //# sourceMappingURL=sort.js.map