formatLocation.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const formatPosition = (pos) => {
  7. if(pos === null)
  8. return "";
  9. const typeOfPos = typeof pos;
  10. switch(typeOfPos) {
  11. case "string":
  12. return pos;
  13. case "number":
  14. return `${pos}`;
  15. case "object":
  16. if(typeof pos.line === "number" && typeof pos.column === "number")
  17. return `${pos.line}:${pos.column}`;
  18. else if(typeof pos.line === "number")
  19. return `${pos.line}:?`;
  20. else if(typeof pos.index === "number")
  21. return `+${pos.index}`;
  22. else
  23. return "";
  24. default:
  25. return "";
  26. }
  27. };
  28. const formatLocation = (loc) => {
  29. if(loc === null)
  30. return "";
  31. const typeOfLoc = typeof loc;
  32. switch(typeOfLoc) {
  33. case "string":
  34. return loc;
  35. case "number":
  36. return `${loc}`;
  37. case "object":
  38. if(loc.start && loc.end) {
  39. if(typeof loc.start.line === "number" && typeof loc.end.line === "number" && typeof loc.end.column === "number" && loc.start.line === loc.end.line)
  40. return `${formatPosition(loc.start)}-${loc.end.column}`;
  41. return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`;
  42. }
  43. if(loc.start)
  44. return formatPosition(loc.start);
  45. return formatPosition(loc);
  46. default:
  47. return "";
  48. }
  49. };
  50. module.exports = formatLocation;