Skip to content

Commit

Permalink
Fix: add parentheses in no-extra-boolean-cast autofixer (fixes #7912) (
Browse files Browse the repository at this point in the history
  • Loading branch information
sprzybylski authored and nzakas committed Jan 14, 2017
1 parent b3f2094 commit 6448ba0
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
15 changes: 14 additions & 1 deletion lib/rules/no-extra-boolean-cast.js
Expand Up @@ -5,6 +5,12 @@

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("../ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand Down Expand Up @@ -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));
}
});
}
}
Expand Down
40 changes: 40 additions & 0 deletions tests/lib/rules/no-extra-boolean-cast.js
Expand Up @@ -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"
}]
}
]
});

0 comments on commit 6448ba0

Please sign in to comment.