location.js.flow 664 B

123456789101112131415161718192021222324252627
  1. // @flow strict
  2. import { type Source } from './source';
  3. /**
  4. * Represents a location in a Source.
  5. */
  6. export type SourceLocation = {|
  7. +line: number,
  8. +column: number,
  9. |};
  10. /**
  11. * Takes a Source and a UTF-8 character offset, and returns the corresponding
  12. * line and column as a SourceLocation.
  13. */
  14. export function getLocation(source: Source, position: number): SourceLocation {
  15. const lineRegexp = /\r\n|[\n\r]/g;
  16. let line = 1;
  17. let column = position + 1;
  18. let match;
  19. while ((match = lineRegexp.exec(source.body)) && match.index < position) {
  20. line += 1;
  21. column = position + 1 - (match.index + match[0].length);
  22. }
  23. return { line, column };
  24. }