index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @typedef {import('unist').Node} Node
  3. * @typedef {import('unist').Point} Point
  4. * @typedef {import('unist').Position} Position
  5. */
  6. /**
  7. * @typedef NodeLike
  8. * @property {string} type
  9. * @property {PositionLike | null | undefined} [position]
  10. *
  11. * @typedef PointLike
  12. * @property {number | null | undefined} [line]
  13. * @property {number | null | undefined} [column]
  14. * @property {number | null | undefined} [offset]
  15. *
  16. * @typedef PositionLike
  17. * @property {PointLike | null | undefined} [start]
  18. * @property {PointLike | null | undefined} [end]
  19. */
  20. /**
  21. * Serialize the positional info of a point, position (start and end points),
  22. * or node.
  23. *
  24. * @param {Node | NodeLike | Point | PointLike | Position | PositionLike | null | undefined} [value]
  25. * Node, position, or point.
  26. * @returns {string}
  27. * Pretty printed positional info of a node (`string`).
  28. *
  29. * In the format of a range `ls:cs-le:ce` (when given `node` or `position`)
  30. * or a point `l:c` (when given `point`), where `l` stands for line, `c` for
  31. * column, `s` for `start`, and `e` for end.
  32. * An empty string (`''`) is returned if the given value is neither `node`,
  33. * `position`, nor `point`.
  34. */
  35. export function stringifyPosition(value) {
  36. // Nothing.
  37. if (!value || typeof value !== 'object') {
  38. return ''
  39. }
  40. // Node.
  41. if ('position' in value || 'type' in value) {
  42. return position(value.position)
  43. }
  44. // Position.
  45. if ('start' in value || 'end' in value) {
  46. return position(value)
  47. }
  48. // Point.
  49. if ('line' in value || 'column' in value) {
  50. return point(value)
  51. }
  52. // ?
  53. return ''
  54. }
  55. /**
  56. * @param {Point | PointLike | null | undefined} point
  57. * @returns {string}
  58. */
  59. function point(point) {
  60. return index(point && point.line) + ':' + index(point && point.column)
  61. }
  62. /**
  63. * @param {Position | PositionLike | null | undefined} pos
  64. * @returns {string}
  65. */
  66. function position(pos) {
  67. return point(pos && pos.start) + '-' + point(pos && pos.end)
  68. }
  69. /**
  70. * @param {number | null | undefined} value
  71. * @returns {number}
  72. */
  73. function index(value) {
  74. return value && typeof value === 'number' ? value : 1
  75. }