Skip to content

Commit

Permalink
feat: find whitespace from operator position to start
Browse files Browse the repository at this point in the history
  • Loading branch information
TrickyPi committed Jul 21, 2024
1 parent 28546b5 commit 5a0a95a
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/ast/nodes/LogicalExpression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type MagicString from 'magic-string';
import { BLANK, EMPTY_ARRAY } from '../../utils/blank';
import {
findFirstOccurrenceOutsideComment,
findLastWhiteSpaceReverse,
findNonWhiteSpace,
type NodeRenderOptions,
removeLineBreaks,
Expand Down Expand Up @@ -185,20 +186,20 @@ export default class LogicalExpression extends NodeBase implements Deoptimizable
}: NodeRenderOptions = BLANK
): void {
if (!this.left.included || !this.right.included) {
const operatorPos = findFirstOccurrenceOutsideComment(
code.original,
this.operator,
this.left.end
);
if (this.right.included) {
const operatorPos = findFirstOccurrenceOutsideComment(
code.original,
this.operator,
this.left.end
);
const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
code.remove(this.start, removePos);
if (preventASI) {
removeLineBreaks(code, removePos, this.right.start);
}
this.left.removeAnnotations(code);
} else {
code.remove(this.left.end, this.end);
code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
}
this.getUsedBranch()!.render(code, options, {
isCalleeOfRenderedParent,
Expand Down
16 changes: 16 additions & 0 deletions src/utils/renderHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ export function findNonWhiteSpace(code: string, index: number): number {
return result.index;
}

const WHITESPACE = /\s/;

export function findLastWhiteSpaceReverse(code: string, start: number, end: number): number {
end--;
while (true) {
if (start + 1 >= end) {
return end;
}
if (WHITESPACE.test(code[end])) {
end--;
} else {
return end;
}
}
}

// This assumes "code" only contains white-space and comments
// Returns position of line-comment if applicable
export function findFirstLineBreakOutsideComment(code: string): [number, number] {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = defineTest({
description: 'remove the white space of the removed part of LogicalExpression',
solo: true
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function App() {
set_class(`abc ${'red'}`);
}

export { App as default };
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default function App() {
let color;
set_class(`abc ${(color || 'red') ?? ''}`);
}

0 comments on commit 5a0a95a

Please sign in to comment.