compareLocations.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
  7. // TODO webpack 5 remove string type from a and b
  8. /**
  9. * Compare two locations
  10. * @param {string|DependencyLocation} a A location node
  11. * @param {string|DependencyLocation} b A location node
  12. * @returns {-1|0|1} sorting comparator value
  13. */
  14. module.exports = (a, b) => {
  15. if (typeof a === "string") {
  16. if (typeof b === "string") {
  17. if (a < b) return -1;
  18. if (a > b) return 1;
  19. return 0;
  20. } else if (typeof b === "object") {
  21. return 1;
  22. } else {
  23. return 0;
  24. }
  25. } else if (typeof a === "object") {
  26. if (typeof b === "string") {
  27. return -1;
  28. } else if (typeof b === "object") {
  29. if ("start" in a && "start" in b) {
  30. const ap = a.start;
  31. const bp = b.start;
  32. if (ap.line < bp.line) return -1;
  33. if (ap.line > bp.line) return 1;
  34. if (ap.column < bp.column) return -1;
  35. if (ap.column > bp.column) return 1;
  36. }
  37. if ("name" in a && "name" in b) {
  38. if (a.name < b.name) return -1;
  39. if (a.name > b.name) return 1;
  40. }
  41. if ("index" in a && "index" in b) {
  42. if (a.index < b.index) return -1;
  43. if (a.index > b.index) return 1;
  44. }
  45. return 0;
  46. } else {
  47. return 0;
  48. }
  49. }
  50. };