Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New: Add no-dupe-else-if rule (fixes #12469) #12504

Merged
merged 4 commits into from Nov 18, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
178 changes: 178 additions & 0 deletions docs/rules/no-dupe-else-if.md
@@ -0,0 +1,178 @@
# Disallow duplicate conditions in `if-else-if` chains (no-dupe-else-if)

`if-else-if` chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions.

```js
if (a) {
foo();
} else if (b) {
bar();
} else if (c) {
baz();
}
```

Two identical test conditions in the same chain are almost always a mistake in the code. Unless there are side effects in the expressions, a duplicate will evaluate to the same `true` or `false` value as the identical expression earlier in the chain, meaning that its branch can never execute.

```js
if (a) {
foo();
} else if (b) {
bar();
} else if (b) {
baz();
}
```

In the above example, `baz()` can never execute. Obviously, `baz()` could be executed only when `b` evaluates to `true`, but in that case `bar()` would be executed instead, since it's earlier in the chain.

## Rule Details

This rule disallows duplicate conditions in the same `if-else-if` chain.

Examples of **incorrect** code for this rule:

```js
/*eslint no-dupe-else-if: "error"*/

if (isSomething(x)) {
foo();
} else if (isSomething(x)) {
bar();
}

if (a) {
foo();
} else if (b) {
bar();
} else if (c && d) {
baz();
} else if (c && d) {
quux();
} else {
quuux();
}

if (n === 1) {
foo();
} else if (n === 2) {
bar();
} else if (n === 3) {
baz();
} else if (n === 2) {
quux();
} else if (n === 5) {
quuux();
}
```

Examples of **correct** code for this rule:

```js
/*eslint no-dupe-else-if: "error"*/

if (isSomething(x)) {
foo();
} else if (isSomethingElse(x)) {
bar();
}

if (a) {
foo();
} else if (b) {
bar();
} else if (c && d) {
baz();
} else if (c && e) {
quux();
} else {
quuux();
}

if (n === 1) {
foo();
} else if (n === 2) {
bar();
} else if (n === 3) {
baz();
} else if (n === 4) {
quux();
} else if (n === 5) {
quuux();
}
```

This rule can also detect some cases where the conditions are not identical, but the branch can never execute due to the logic of `||` and `&&` operators.

Examples of additional **incorrect** code for this rule:

```js
/*eslint no-dupe-else-if: "error"*/

if (a || b) {
foo();
} else if (a) {
bar();
}

if (a) {
foo();
} else if (b) {
bar();
} else if (a || b) {
baz();
}

if (a) {
foo();
} else if (a && b) {
bar();
}

if (a && b) {
foo();
} else if (a && b && c) {
bar();
}

if (a || b) {
foo();
} else if (b && c) {
bar();
}

if (a) {
foo();
} else if (b && c) {
bar();
} else if (d && (c && e && b || a)) {
baz();
}
```

Please note that this rule does not compare conditions from the chain with conditions inside statements, and will not warn in the cases such as follows:

```js
if (a) {
if (a) {
foo();
}
}

if (a) {
foo();
} else {
if (a) {
bar();
}
}
```

## When Not To Use It

In rare cases where you really need identical test conditions in the same chain, which necessarily means that the expressions in the chain are causing and relying on side effects, you will have to turn this rule off.

## Related Rules

* [no-duplicate-case](no-duplicate-case.md)
* [no-lonely-if](no-lonely-if.md)
1 change: 1 addition & 0 deletions lib/rules/index.js
Expand Up @@ -108,6 +108,7 @@ module.exports = new LazyLoadingRuleMap(Object.entries({
"no-div-regex": () => require("./no-div-regex"),
"no-dupe-args": () => require("./no-dupe-args"),
"no-dupe-class-members": () => require("./no-dupe-class-members"),
"no-dupe-else-if": () => require("./no-dupe-else-if"),
"no-dupe-keys": () => require("./no-dupe-keys"),
"no-duplicate-case": () => require("./no-duplicate-case"),
"no-duplicate-imports": () => require("./no-duplicate-imports"),
Expand Down
122 changes: 122 additions & 0 deletions lib/rules/no-dupe-else-if.js
@@ -0,0 +1,122 @@
/**
* @fileoverview Rule to disallow duplicate conditions in if-else-if chains
* @author Milos Djermanovic
*/

"use strict";

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

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

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
* Determines whether the first given array is a subset of the second given array.
* @param {Function} comparator A function to compare two elements, should return `true` if they are equal.
* @param {Array} arrA The array to compare from.
* @param {Array} arrB The array to compare against.
* @returns {boolean} `true` if the array `arrA` is a subset of the array `arrB`.
*/
function isSubsetByComparator(comparator, arrA, arrB) {
return arrA.every(a => arrB.some(b => comparator(a, b)));
}

/**
* Splits the given node by the given logical operator.
* @param {string} operator Logical operator `||` or `&&`.
* @param {ASTNode} node The node to split.
* @returns {ASTNode[]} Array of conditions that makes the node when joined by the operator.
*/
function splitByLogicalOperator(operator, node) {
if (node.type === "LogicalExpression" && node.operator === operator) {
return [...splitByLogicalOperator(operator, node.left), ...splitByLogicalOperator(operator, node.right)];
}
return [node];
}

const splitByOr = splitByLogicalOperator.bind(null, "||");
const splitByAnd = splitByLogicalOperator.bind(null, "&&");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
meta: {
type: "problem",

docs: {
description: "disallow duplicate conditions in if-else-if chains",
category: "Possible Errors",
recommended: false,
url: "https://eslint.org/docs/rules/no-dupe-else-if"
},

schema: [],

messages: {
unexpected: "This branch can never execute, its condition is a duplicate or covered by previous conditions in the if-else-if chain."
kaicataldo marked this conversation as resolved.
Show resolved Hide resolved
}
},

create(context) {
const sourceCode = context.getSourceCode();

/**
* Determines whether the two given nodes are considered to be equal. In particular, given that the nodes
* represent expressions in a boolean context, `||` and `&&` can be considered as commutative operators.
* @param {ASTNode} a First node.
* @param {ASTNode} b Second node.
* @returns {boolean} `true` if the nodes are considered to be equal.
*/
function equal(a, b) {
if (a.type !== b.type) {
return false;
}

if (
a.type === "LogicalExpression" &&
(a.operator === "||" || a.operator === "&&") &&
a.operator === b.operator
) {
return equal(a.left, b.left) && equal(a.right, b.right) ||
equal(a.left, b.right) && equal(a.right, b.left);
}

return astUtils.equalTokens(a, b, sourceCode);
}

const isSubset = isSubsetByComparator.bind(null, equal);

return {
IfStatement(node) {
const test = node.test,
conditionsToCheck = test.type === "LogicalExpression" && test.operator === "&&"
? [test, ...splitByAnd(test)]
: [test];
let current = node,
listToCheck = conditionsToCheck.map(c => splitByOr(c).map(splitByAnd));

while (current.parent && current.parent.type === "IfStatement" && current.parent.alternate === current) {
current = current.parent;

const currentConditions = splitByOr(current.test).map(splitByAnd);

listToCheck = listToCheck.map(e => e.filter(
lc => !currentConditions.some(cc => isSubset(cc, lc))
aladdin-add marked this conversation as resolved.
Show resolved Hide resolved
));

if (listToCheck.some(e => e.length === 0)) {
aladdin-add marked this conversation as resolved.
Show resolved Hide resolved
context.report({ node: test, messageId: "unexpected" });
break;
}
}
}
};
}
};