index.js 2.0 KB

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