Skip to content

Commit 6871129

Browse files
committed
address review comments
1 parent 33d1265 commit 6871129

1 file changed

Lines changed: 36 additions & 12 deletions

File tree

eslint-plugin-prettier.js

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
*/
1313

1414
/**
15-
* @typedef {{ line: number; column: number; offset: number; }} Location
16-
*
15+
* @typedef {{ line: number; column: number; offset: number }} Location
1716
*
1817
* @typedef {PrettierOptions & {
1918
* onDiskFilepath: string;
@@ -30,7 +29,9 @@
3029
* ) => string} PrettierFormat
3130
*
3231
*
33-
* @typedef {Parameters<Exclude<ESLint.Plugin['rules'], undefined>[string]['create']>[0]} RuleContext
32+
* @typedef {Parameters<
33+
* Exclude<ESLint.Plugin['rules'], undefined>[string]['create']
34+
* >[0]} RuleContext
3435
*/
3536

3637
'use strict';
@@ -97,15 +98,38 @@ function reportDifference(context, difference) {
9798
// with the `sourceCode` property.
9899
// TODO: Only use property when our eslint peerDependency is >=8.40.0.
99100
const sourceCode = context.sourceCode ?? context.getSourceCode();
100-
if (!('text' in sourceCode)) {
101-
throw new Error('prettier/prettier: non-textual source code is unsupported');
102-
}
103101

104-
const lineIndexes = [...sourceCode.text.matchAll(/\n/g)].map(match => match.index);
105-
// first line in the file starts at byte offset 0
106-
lineIndexes.unshift(0);
107-
const [start, end] = range.map(index =>
108-
getLocFromOffset(lineIndexes, index)
102+
const lazy = {
103+
/**
104+
* Lazily computes the line indices for `sourceCode`.
105+
*
106+
* @returns {number[]}
107+
*/
108+
get lineIndexes() {
109+
// @ts-ignore
110+
delete this.lineIndexes;
111+
112+
if (!('text' in sourceCode)) {
113+
throw new Error(
114+
'prettier/prettier: non-textual source code is unsupported',
115+
);
116+
}
117+
118+
// @ts-ignore
119+
this.lineIndexes = [...sourceCode.text.matchAll(/\n/g)].map(
120+
match => match.index,
121+
);
122+
// first line in the file starts at byte offset 0
123+
this.lineIndexes.unshift(0);
124+
return this.lineIndexes;
125+
},
126+
};
127+
128+
const [start, end] = range.map(
129+
index =>
130+
// @ts-ignore
131+
sourceCode.getLocFromIndex?.(index) ??
132+
getLocFromOffset(lazy.lineIndexes, index),
109133
);
110134

111135
context.report({
@@ -284,7 +308,7 @@ const eslintPluginPrettier = {
284308

285309
for (const difference of differences) {
286310
reportDifference(
287-
/** @type {Rule.RuleContext} */(context),
311+
/** @type {Rule.RuleContext} */ (context),
288312
difference,
289313
);
290314
}

0 commit comments

Comments
 (0)