utils.ts 805 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. export function convertIndexToLineCh(
  2. text: string,
  3. i: number
  4. ): { line: number; ch: number } {
  5. const lines = text.split("\n")
  6. let line = 0
  7. let counter = 0
  8. while (line < lines.length) {
  9. if (i > lines[line].length + counter) {
  10. counter += lines[line].length + 1
  11. line++
  12. } else {
  13. return {
  14. line: line + 1,
  15. ch: i - counter + 1,
  16. }
  17. }
  18. }
  19. throw new Error("Invalid input")
  20. }
  21. export function convertLineChToIndex(
  22. text: string,
  23. lineCh: { line: number; ch: number }
  24. ): number {
  25. const textSplit = text.split("\n")
  26. if (textSplit.length < lineCh.line) throw new Error("Invalid position")
  27. const tillLineIndex = textSplit
  28. .slice(0, lineCh.line)
  29. .reduce((acc, line) => acc + line.length + 1, 0)
  30. return tillLineIndex + lineCh.ch
  31. }