diff --git a/lib/rules/no-extra-boolean-cast.js b/lib/rules/no-extra-boolean-cast.js index 123a7cacc52..e7368b07b4c 100644 --- a/lib/rules/no-extra-boolean-cast.js +++ b/lib/rules/no-extra-boolean-cast.js @@ -5,6 +5,12 @@ "use strict"; +//------------------------------------------------------------------------------ +// Requirements +//------------------------------------------------------------------------------ + +const astUtils = require("../ast-utils"); + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -91,7 +97,14 @@ module.exports = { context.report({ node, message: "Redundant Boolean call.", - fix: fixer => fixer.replaceText(node, sourceCode.getText(node.arguments[0])) + fix: fixer => { + const argument = node.arguments[0]; + + if (astUtils.getPrecedence(argument) < astUtils.getPrecedence(node.parent)) { + return fixer.replaceText(node, `(${sourceCode.getText(argument)})`); + } + return fixer.replaceText(node, sourceCode.getText(argument)); + } }); } } diff --git a/tests/lib/rules/no-extra-boolean-cast.js b/tests/lib/rules/no-extra-boolean-cast.js index 9623daa6554..71a62680420 100644 --- a/tests/lib/rules/no-extra-boolean-cast.js +++ b/tests/lib/rules/no-extra-boolean-cast.js @@ -146,6 +146,46 @@ ruleTester.run("no-extra-boolean-cast", rule, { message: "Redundant Boolean call.", type: "CallExpression" }] + }, + { + code: "!Boolean(foo && bar)", + output: "!(foo && bar)", + errors: [{ + message: "Redundant Boolean call.", + type: "CallExpression" + }] + }, + { + code: "!Boolean(foo + bar)", + output: "!(foo + bar)", + errors: [{ + message: "Redundant Boolean call.", + type: "CallExpression" + }] + }, + { + code: "!Boolean(+foo)", + output: "!+foo", + errors: [{ + message: "Redundant Boolean call.", + type: "CallExpression" + }] + }, + { + code: "!Boolean(foo())", + output: "!foo()", + errors: [{ + message: "Redundant Boolean call.", + type: "CallExpression" + }] + }, + { + code: "!Boolean(foo = bar)", + output: "!(foo = bar)", + errors: [{ + message: "Redundant Boolean call.", + type: "CallExpression" + }] } ] });