location.js 790 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.getLocation = getLocation;
  6. var _invariant = require('../jsutils/invariant.js');
  7. const LineRegExp = /\r\n|[\n\r]/g;
  8. /**
  9. * Represents a location in a Source.
  10. */
  11. /**
  12. * Takes a Source and a UTF-8 character offset, and returns the corresponding
  13. * line and column as a SourceLocation.
  14. */
  15. function getLocation(source, position) {
  16. let lastLineStart = 0;
  17. let line = 1;
  18. for (const match of source.body.matchAll(LineRegExp)) {
  19. typeof match.index === 'number' || (0, _invariant.invariant)(false);
  20. if (match.index >= position) {
  21. break;
  22. }
  23. lastLineStart = match.index + match[0].length;
  24. line += 1;
  25. }
  26. return {
  27. line,
  28. column: position + 1 - lastLineStart,
  29. };
  30. }