UNPKG

2.63 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow negating the left operand of relational operators
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("../ast-utils");
13
14//------------------------------------------------------------------------------
15// Helpers
16//------------------------------------------------------------------------------
17
18/**
19 * Checks whether the given operator is a relational operator or not.
20 *
21 * @param {string} op - The operator type to check.
22 * @returns {boolean} `true` if the operator is a relational operator.
23 */
24function isRelationalOperator(op) {
25 return op === "in" || op === "instanceof";
26}
27
28/**
29 * Checks whether the given node is a logical negation expression or not.
30 *
31 * @param {ASTNode} node - The node to check.
32 * @returns {boolean} `true` if the node is a logical negation expression.
33 */
34function isNegation(node) {
35 return node.type === "UnaryExpression" && node.operator === "!";
36}
37
38//------------------------------------------------------------------------------
39// Rule Definition
40//------------------------------------------------------------------------------
41
42module.exports = {
43 meta: {
44 docs: {
45 description: "disallow negating the left operand of relational operators",
46 category: "Possible Errors",
47 recommended: false
48 },
49 schema: [],
50 fixable: "code"
51 },
52
53 create(context) {
54 const sourceCode = context.getSourceCode();
55
56 return {
57 BinaryExpression(node) {
58 if (isRelationalOperator(node.operator) &&
59 isNegation(node.left) &&
60 !astUtils.isParenthesised(sourceCode, node.left)
61 ) {
62 context.report({
63 node,
64 loc: node.left.loc,
65 message: "Unexpected negating the left operand of '{{operator}}' operator.",
66 data: node,
67
68 fix(fixer) {
69 const negationToken = sourceCode.getFirstToken(node.left);
70 const fixRange = [negationToken.range[1], node.range[1]];
71 const text = sourceCode.text.slice(fixRange[0], fixRange[1]);
72
73 return fixer.replaceTextRange(fixRange, `(${text})`);
74 }
75 });
76 }
77 }
78 };
79 }
80};