From 4c607777a9cdb48f7aea543286bd51207baf672c Mon Sep 17 00:00:00 2001 From: Lukas Taegert-Atkinson Date: Sat, 16 Jan 2021 07:11:07 +0100 Subject: [PATCH] Correctly simplify assignments with parentheses --- src/ast/nodes/AssignmentExpression.ts | 3 ++- src/utils/renderHelpers.ts | 7 ++++--- .../samples/unused-parenthesed-assignment/_config.js | 6 ++++++ .../function/samples/unused-parenthesed-assignment/main.js | 2 ++ 4 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 test/function/samples/unused-parenthesed-assignment/_config.js create mode 100644 test/function/samples/unused-parenthesed-assignment/main.js diff --git a/src/ast/nodes/AssignmentExpression.ts b/src/ast/nodes/AssignmentExpression.ts index 3b0f57aa7b7..e30ccf7aa1e 100644 --- a/src/ast/nodes/AssignmentExpression.ts +++ b/src/ast/nodes/AssignmentExpression.ts @@ -76,7 +76,8 @@ export default class AssignmentExpression extends NodeBase { this.right.render(code, options, { renderedParentType: renderedParentType || this.parent.type }); - code.remove(this.start, this.right.start); + const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', this.left.end); + code.remove(this.start, findNonWhiteSpace(code.original, operatorPos + 1)); } if (options.format === 'system') { const exportNames = diff --git a/src/utils/renderHelpers.ts b/src/utils/renderHelpers.ts index 28021367797..a52ba90c62f 100644 --- a/src/utils/renderHelpers.ts +++ b/src/utils/renderHelpers.ts @@ -50,11 +50,12 @@ export function findFirstOccurrenceOutsideComment(code: string, searchString: st } } -const WHITESPACE = /\s/; +const NON_WHITESPACE = /\S/g; export function findNonWhiteSpace(code: string, index: number) { - while (index < code.length && WHITESPACE.test(code[index])) index++; - return index; + NON_WHITESPACE.lastIndex = index; + const result = NON_WHITESPACE.exec(code)!; + return result.index; } // This assumes "code" only contains white-space and comments diff --git a/test/function/samples/unused-parenthesed-assignment/_config.js b/test/function/samples/unused-parenthesed-assignment/_config.js new file mode 100644 index 00000000000..24d8c766197 --- /dev/null +++ b/test/function/samples/unused-parenthesed-assignment/_config.js @@ -0,0 +1,6 @@ +module.exports = { + description: 'correctly simplifies assignments with right-hand-sides in parentheses (#3924)', + context: { + someObject: { isTrue: true } + } +}; diff --git a/test/function/samples/unused-parenthesed-assignment/main.js b/test/function/samples/unused-parenthesed-assignment/main.js new file mode 100644 index 00000000000..051552cb174 --- /dev/null +++ b/test/function/samples/unused-parenthesed-assignment/main.js @@ -0,0 +1,2 @@ +let unused = false; +unused = (someObject.isTrue === true);