index.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var LF = '\n';
  2. var CR = '\r';
  3. var LinesAndColumns = (function () {
  4. function LinesAndColumns(string) {
  5. this.string = string;
  6. var offsets = [0];
  7. for (var offset = 0; offset < string.length;) {
  8. switch (string[offset]) {
  9. case LF:
  10. offset += LF.length;
  11. offsets.push(offset);
  12. break;
  13. case CR:
  14. offset += CR.length;
  15. if (string[offset] === LF) {
  16. offset += LF.length;
  17. }
  18. offsets.push(offset);
  19. break;
  20. default:
  21. offset++;
  22. break;
  23. }
  24. }
  25. this.offsets = offsets;
  26. }
  27. LinesAndColumns.prototype.locationForIndex = function (index) {
  28. if (index < 0 || index > this.string.length) {
  29. return null;
  30. }
  31. var line = 0;
  32. var offsets = this.offsets;
  33. while (offsets[line + 1] <= index) {
  34. line++;
  35. }
  36. var column = index - offsets[line];
  37. return { line: line, column: column };
  38. };
  39. LinesAndColumns.prototype.indexForLocation = function (location) {
  40. var line = location.line, column = location.column;
  41. if (line < 0 || line >= this.offsets.length) {
  42. return null;
  43. }
  44. if (column < 0 || column > this.lengthOfLine(line)) {
  45. return null;
  46. }
  47. return this.offsets[line] + column;
  48. };
  49. LinesAndColumns.prototype.lengthOfLine = function (line) {
  50. var offset = this.offsets[line];
  51. var nextOffset = line === this.offsets.length - 1 ? this.string.length : this.offsets[line + 1];
  52. return nextOffset - offset;
  53. };
  54. return LinesAndColumns;
  55. }());
  56. export default LinesAndColumns;