index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict'
  2. module.exports = factory
  3. function factory(file) {
  4. var contents = indices(String(file))
  5. return {
  6. toPosition: offsetToPositionFactory(contents),
  7. toOffset: positionToOffsetFactory(contents)
  8. }
  9. }
  10. // Factory to get the line and column-based `position` for `offset` in the bound
  11. // indices.
  12. function offsetToPositionFactory(indices) {
  13. return offsetToPosition
  14. // Get the line and column-based `position` for `offset` in the bound indices.
  15. function offsetToPosition(offset) {
  16. var index = -1
  17. var length = indices.length
  18. if (offset < 0) {
  19. return {}
  20. }
  21. while (++index < length) {
  22. if (indices[index] > offset) {
  23. return {
  24. line: index + 1,
  25. column: offset - (indices[index - 1] || 0) + 1,
  26. offset: offset
  27. }
  28. }
  29. }
  30. return {}
  31. }
  32. }
  33. // Factory to get the `offset` for a line and column-based `position` in the
  34. // bound indices.
  35. function positionToOffsetFactory(indices) {
  36. return positionToOffset
  37. // Get the `offset` for a line and column-based `position` in the bound
  38. // indices.
  39. function positionToOffset(position) {
  40. var line = position && position.line
  41. var column = position && position.column
  42. if (!isNaN(line) && !isNaN(column) && line - 1 in indices) {
  43. return (indices[line - 2] || 0) + column - 1 || 0
  44. }
  45. return -1
  46. }
  47. }
  48. // Get indices of line-breaks in `value`.
  49. function indices(value) {
  50. var result = []
  51. var index = value.indexOf('\n')
  52. while (index !== -1) {
  53. result.push(index + 1)
  54. index = value.indexOf('\n', index + 1)
  55. }
  56. result.push(value.length + 1)
  57. return result
  58. }