location.mjs 664 B

123456789101112131415161718192021222324252627282930
  1. import { invariant } from '../jsutils/invariant.mjs';
  2. const LineRegExp = /\r\n|[\n\r]/g;
  3. /**
  4. * Represents a location in a Source.
  5. */
  6. /**
  7. * Takes a Source and a UTF-8 character offset, and returns the corresponding
  8. * line and column as a SourceLocation.
  9. */
  10. export function getLocation(source, position) {
  11. let lastLineStart = 0;
  12. let line = 1;
  13. for (const match of source.body.matchAll(LineRegExp)) {
  14. typeof match.index === 'number' || invariant(false);
  15. if (match.index >= position) {
  16. break;
  17. }
  18. lastLineStart = match.index + match[0].length;
  19. line += 1;
  20. }
  21. return {
  22. line,
  23. column: position + 1 - lastLineStart,
  24. };
  25. }