-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
no-unused-expressions.js
64 lines (55 loc) 路 1.7 KB
/
no-unused-expressions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import ruleComposer from "eslint-rule-composer";
import eslint from "eslint";
const rule = new eslint.Linter().getRules().get("no-unused-expressions");
/**
* @param {ASTNode} node - any node
* @returns {boolean} whether the given node is either an IfStatement or an
* ExpressionStatement and is the last node in the body of a BlockStatement
*/
function isFinalStatementInBlockStatement(node) {
const parent = node.parent;
return (
/^(?:If|Expression)Statement$/.test(node.type) &&
parent.type === "BlockStatement" &&
parent.body[parent.body.length - 1] === node
);
}
/**
* @param {ASTNode} node - any node
* @returns {boolean} whether the given node represents an unbroken chain of
* tail ExpressionStatements and IfStatements within a DoExpression
* https://github.com/tc39/proposal-do-expressions
*/
function isInDoStatement(node) {
if (!node) return false;
if (node.type === "DoExpression") return true;
// this is an `else if`
if (
node.type === "IfStatement" &&
node.parent &&
node.parent.type === "IfStatement"
) {
return isInDoStatement(node.parent);
}
if (isFinalStatementInBlockStatement(node)) {
return isInDoStatement(node.parent.parent);
}
return false;
}
/**
* @param {ASTNode} node - any node
* @returns {boolean} whether the given node is an optional call expression,
* https://github.com/tc39/proposal-optional-chaining
*/
function isOptionalCallExpression(node) {
return (
!!node &&
node.type === "ExpressionStatement" &&
node.expression.type === "OptionalCallExpression"
);
}
export default ruleComposer.filterReports(
rule,
problem =>
!isInDoStatement(problem.node) && !isOptionalCallExpression(problem.node),
);