Skip to content

Commit

Permalink
Fix: no-mixed-operators false positives with ? : (fixes #14223) (#1…
Browse files Browse the repository at this point in the history
  • Loading branch information
mdjermanovic committed Mar 24, 2021
1 parent a99eb2d commit 28583eb
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 24 deletions.
9 changes: 9 additions & 0 deletions docs/rules/no-mixed-operators.md
Expand Up @@ -122,6 +122,10 @@ var foo = a & b | c;
/*eslint no-mixed-operators: ["error", {"groups": [["&&", "||", "?:"]]}]*/

var foo = a || b ? c : d;

var bar = a ? b || c : d;

var baz = a ? b : c || d;
```

Examples of **correct** code for this rule with `{"groups": [["&", "|", "^", "~", "<<", ">>", ">>>"], ["&&", "||"]]}` option:
Expand All @@ -145,6 +149,11 @@ var foo = (a + b) * c;

var foo = (a || b) ? c : d;
var foo = a || (b ? c : d);

var bar = a ? (b || c) : d;

var baz = a ? b : (c || d);
var baz = (a ? b : c) || d;
```

### allowSamePrecedence
Expand Down
29 changes: 6 additions & 23 deletions lib/rules/no-mixed-operators.js
Expand Up @@ -161,17 +161,6 @@ module.exports = {
);
}

/**
* Checks whether the operator of a given node is mixed with a
* conditional expression.
* @param {ASTNode} node A node to check. This is a conditional
* expression node
* @returns {boolean} `true` if the node was mixed.
*/
function isMixedWithConditionalParent(node) {
return !astUtils.isParenthesised(sourceCode, node) && !astUtils.isParenthesised(sourceCode, node.test);
}

/**
* Gets the operator token of a given node.
* @param {ASTNode} node A node to check. This is a BinaryExpression
Expand Down Expand Up @@ -220,19 +209,13 @@ module.exports = {
* @returns {void}
*/
function check(node) {
if (TARGET_NODE_TYPE.test(node.parent.type)) {
if (node.parent.type === "ConditionalExpression" && !shouldIgnore(node) && isMixedWithConditionalParent(node.parent)) {
reportBothOperators(node);
} else {
if (TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}
}
if (
TARGET_NODE_TYPE.test(node.parent.type) &&
isMixedWithParent(node) &&
!shouldIgnore(node)
) {
reportBothOperators(node);
}

}

return {
Expand Down
18 changes: 17 additions & 1 deletion tests/lib/rules/no-mixed-operators.js
Expand Up @@ -52,13 +52,29 @@ ruleTester.run("no-mixed-operators", rule, {
code: "(a || b) ? c : d",
options: [{ groups: [["&&", "||", "?:"]] }]
},
{
code: "a ? (b || c) : d",
options: [{ groups: [["&&", "||", "?:"]] }]
},
{
code: "a ? b : (c || d)",
options: [{ groups: [["&&", "||", "?:"]] }]
},
{
code: "a || (b ? c : d)",
options: [{ groups: [["&&", "||", "?:"]] }]
},
{
code: "(a ? b : c) || d",
options: [{ groups: [["&&", "||", "?:"]] }]
},
"a || (b ? c : d)",
"(a || b) ? c : d",
"a || b ? c : d"
"a || b ? c : d",
"a ? (b || c) : d",
"a ? b || c : d",
"a ? b : (c || d)",
"a ? b : c || d"
],
invalid: [
{
Expand Down

0 comments on commit 28583eb

Please sign in to comment.