Skip to content

Commit 159d1be

Browse files
lilnasyoverlookmotel
authored andcommitted
refactor : no branching, collect slice start and end
1 parent 3f95f0d commit 159d1be

File tree

1 file changed

+23
-20
lines changed

1 file changed

+23
-20
lines changed

apps/oxlint/src-js/plugins/source_code.ts

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -174,40 +174,43 @@ export const SOURCE_CODE = Object.freeze({
174174
getCommentsBefore(nodeOrToken: NodeOrToken): Comment[] {
175175
if (ast === null) initAst();
176176
const { comments } = ast;
177-
if (comments.length === 0) return [];
178-
const targetStart = nodeOrToken.start;
179177

180-
const commentsBefore: Comment[] = [];
178+
const commentsLength = comments.length;
179+
let targetStart = nodeOrToken.start;
180+
181+
let sliceStart = commentsLength;
182+
let sliceEnd = 0;
181183

182184
// Reverse iteration isn't ideal, but this entire implementation may need to be rewritten
183185
// with token-based APIs to match eslint.
184-
for (let i = comments.length - 1; i >= 0; i--) {
186+
for (let i = commentsLength - 1; i >= 0; i--) {
185187
const comment = comments[i];
186188
const commentEnd = comment.end;
187189

188-
if (commentEnd > targetStart) {
189-
continue;
190+
if (commentEnd < targetStart) {
191+
const gap = sourceText.slice(commentEnd, targetStart);
192+
const whitespaceOnlyGap = whitespacePattern.test(gap);
193+
if (whitespaceOnlyGap) {
194+
sliceStart = sliceEnd = i + 1;
195+
targetStart = comment.start;
196+
}
197+
break;
190198
}
199+
}
191200

192-
const whitespaceOnlyGap = whitespacePattern.test(sourceText.slice(commentEnd, targetStart));
201+
for (let i = sliceEnd - 1; i >= 0; i--) {
202+
const comment = comments[i];
203+
const gap = sourceText.slice(comment.end, targetStart);
204+
const whitespaceOnlyGap = whitespacePattern.test(gap);
193205
if (whitespaceOnlyGap) {
194-
commentsBefore.unshift(comment);
195-
let currentComment = comment;
196-
for (let j = i - 1; j >= 0; j--) {
197-
const prevComment = comments[j];
198-
const between = sourceText.slice(prevComment.end, currentComment.start);
199-
if (whitespacePattern.test(between)) {
200-
commentsBefore.unshift(prevComment);
201-
currentComment = prevComment;
202-
} else {
203-
break;
204-
}
205-
}
206+
sliceStart = i;
207+
targetStart = comment.start;
208+
} else {
206209
break;
207210
}
208211
}
209212

210-
return commentsBefore;
213+
return comments.slice(sliceStart, sliceEnd);
211214
},
212215

213216
/**

0 commit comments

Comments
 (0)