UNPKG

3.21 kBJavaScriptView Raw
1/**
2 * @fileoverview disallow unncessary concatenation of template strings
3 * @author Henry Zhu
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const astUtils = require("../ast-utils");
12
13//------------------------------------------------------------------------------
14// Helpers
15//------------------------------------------------------------------------------
16
17/**
18 * Checks whether or not a given node is a concatenation.
19 * @param {ASTNode} node - A node to check.
20 * @returns {boolean} `true` if the node is a concatenation.
21 */
22function isConcatenation(node) {
23 return node.type === "BinaryExpression" && node.operator === "+";
24}
25
26/**
27 * Checks if the given token is a `+` token or not.
28 * @param {Token} token - The token to check.
29 * @returns {boolean} `true` if the token is a `+` token.
30 */
31function isConcatOperatorToken(token) {
32 return token.value === "+" && token.type === "Punctuator";
33}
34
35/**
36 * Get's the right most node on the left side of a BinaryExpression with + operator.
37 * @param {ASTNode} node - A BinaryExpression node to check.
38 * @returns {ASTNode} node
39 */
40function getLeft(node) {
41 let left = node.left;
42
43 while (isConcatenation(left)) {
44 left = left.right;
45 }
46 return left;
47}
48
49/**
50 * Get's the left most node on the right side of a BinaryExpression with + operator.
51 * @param {ASTNode} node - A BinaryExpression node to check.
52 * @returns {ASTNode} node
53 */
54function getRight(node) {
55 let right = node.right;
56
57 while (isConcatenation(right)) {
58 right = right.left;
59 }
60 return right;
61}
62
63//------------------------------------------------------------------------------
64// Rule Definition
65//------------------------------------------------------------------------------
66
67module.exports = {
68 meta: {
69 docs: {
70 description: "disallow unnecessary concatenation of literals or template literals",
71 category: "Best Practices",
72 recommended: false,
73 url: "https://eslint.org/docs/rules/no-useless-concat"
74 },
75
76 schema: []
77 },
78
79 create(context) {
80 const sourceCode = context.getSourceCode();
81
82 return {
83 BinaryExpression(node) {
84
85 // check if not concatenation
86 if (node.operator !== "+") {
87 return;
88 }
89
90 // account for the `foo + "a" + "b"` case
91 const left = getLeft(node);
92 const right = getRight(node);
93
94 if (astUtils.isStringLiteral(left) &&
95 astUtils.isStringLiteral(right) &&
96 astUtils.isTokenOnSameLine(left, right)
97 ) {
98 const operatorToken = sourceCode.getFirstTokenBetween(left, right, isConcatOperatorToken);
99
100 context.report({
101 node,
102 loc: operatorToken.loc.start,
103 message: "Unexpected string concatenation of literals."
104 });
105 }
106 }
107 };
108 }
109};