diff --git a/lib/rules/operator-assignment.js b/lib/rules/operator-assignment.js index 63982cf3920..ea6d2905c46 100644 --- a/lib/rules/operator-assignment.js +++ b/lib/rules/operator-assignment.js @@ -194,7 +194,17 @@ module.exports = { ) { rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; } else { - rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]); + const firstRightToken = sourceCode.getFirstToken(node.right); + let rightTextPrefix = ""; + + if ( + operatorToken.range[1] === firstRightToken.range[0] && + !astUtils.canTokensBeAdjacent(newOperator, firstRightToken) + ) { + rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar + } + + rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`; } return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`); diff --git a/tests/lib/rules/operator-assignment.js b/tests/lib/rules/operator-assignment.js index fe7b326a10a..06a0e40e707 100644 --- a/tests/lib/rules/operator-assignment.js +++ b/tests/lib/rules/operator-assignment.js @@ -230,6 +230,31 @@ ruleTester.run("operator-assignment", rule, { output: "foo = foo * (bar + 1)", options: ["never"], errors: UNEXPECTED_OPERATOR_ASSIGNMENT + }, { + code: "foo+=-bar", + output: "foo= foo+-bar", // tokens can be adjacent + options: ["never"], + errors: UNEXPECTED_OPERATOR_ASSIGNMENT + }, { + code: "foo+=+bar", + output: "foo= foo+ +bar", // tokens cannot be adjacent, insert a space between + options: ["never"], + errors: UNEXPECTED_OPERATOR_ASSIGNMENT + }, { + code: "foo+= +bar", + output: "foo= foo+ +bar", // tokens cannot be adjacent, but there is already a space between + options: ["never"], + errors: UNEXPECTED_OPERATOR_ASSIGNMENT + }, { + code: "foo+=/**/+bar", + output: "foo= foo+/**/+bar", // tokens cannot be adjacent, but there is a comment between + options: ["never"], + errors: UNEXPECTED_OPERATOR_ASSIGNMENT + }, { + code: "foo+=+bar===baz", + output: "foo= foo+(+bar===baz)", // tokens cannot be adjacent, but the right side will be parenthesised + options: ["never"], + errors: UNEXPECTED_OPERATOR_ASSIGNMENT }] });