]>
git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-useless-concat.js
26c5206df365a98ebe5d10b7e42ed8c09d438d0e
2 * @fileoverview disallow unnecessary concatenation of template strings
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils
= require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
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.
22 function isConcatenation(node
) {
23 return node
.type
=== "BinaryExpression" && node
.operator
=== "+";
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.
31 function isConcatOperatorToken(token
) {
32 return token
.value
=== "+" && token
.type
=== "Punctuator";
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
40 function getLeft(node
) {
43 while (isConcatenation(left
)) {
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
54 function getRight(node
) {
55 let right
= node
.right
;
57 while (isConcatenation(right
)) {
63 //------------------------------------------------------------------------------
65 //------------------------------------------------------------------------------
67 /** @type {import('../shared/types').Rule} */
73 description
: "Disallow unnecessary concatenation of literals or template literals",
75 url
: "https://eslint.org/docs/rules/no-useless-concat"
81 unexpectedConcat
: "Unexpected string concatenation of literals."
86 const sourceCode
= context
.getSourceCode();
89 BinaryExpression(node
) {
91 // check if not concatenation
92 if (node
.operator
!== "+") {
96 // account for the `foo + "a" + "b"` case
97 const left
= getLeft(node
);
98 const right
= getRight(node
);
100 if (astUtils
.isStringLiteral(left
) &&
101 astUtils
.isStringLiteral(right
) &&
102 astUtils
.isTokenOnSameLine(left
, right
)
104 const operatorToken
= sourceCode
.getFirstTokenBetween(left
, right
, isConcatOperatorToken
);
108 loc
: operatorToken
.loc
,
109 messageId
: "unexpectedConcat"