Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getLocation: use more explicit matchAll instead of RegExp.exec #3105

Merged
merged 1 commit into from May 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.yml
Expand Up @@ -577,7 +577,7 @@ overrides:
'@typescript-eslint/prefer-readonly': error
'@typescript-eslint/prefer-readonly-parameter-types': off # TODO consider
'@typescript-eslint/prefer-reduce-type-parameter': error
'@typescript-eslint/prefer-regexp-exec': error
'@typescript-eslint/prefer-regexp-exec': off
'@typescript-eslint/prefer-ts-expect-error': error
'@typescript-eslint/prefer-string-starts-ends-with': off # TODO switch to error after IE11 drop
'@typescript-eslint/promise-function-async': off
Expand Down
17 changes: 11 additions & 6 deletions src/language/location.js
@@ -1,5 +1,7 @@
import type { Source } from './source';

const LineRegExp = /\r\n|[\n\r]/g;

/**
* Represents a location in a Source.
*/
Expand All @@ -13,13 +15,16 @@ export type SourceLocation = {
* line and column as a SourceLocation.
*/
export function getLocation(source: Source, position: number): SourceLocation {
const lineRegexp = /\r\n|[\n\r]/g;
let lastLineStart = 0;
let line = 1;
let column = position + 1;
let match;
while ((match = lineRegexp.exec(source.body)) && match.index < position) {

for (const match of source.body.matchAll(LineRegExp)) {
if (match.index >= position) {
break;
}
lastLineStart = match.index + match[0].length;
line += 1;
column = position + 1 - (match.index + match[0].length);
}
return { line, column };

return { line, column: position + 1 - lastLineStart };
}