123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- "use strict";
- const astUtils = require("./utils/ast-utils");
- function isConcatenation(node) {
- return node.type === "BinaryExpression" && node.operator === "+";
- }
- function isConcatOperatorToken(token) {
- return token.value === "+" && token.type === "Punctuator";
- }
- function getLeft(node) {
- let left = node.left;
- while (isConcatenation(left)) {
- left = left.right;
- }
- return left;
- }
- function getRight(node) {
- let right = node.right;
- while (isConcatenation(right)) {
- right = right.left;
- }
- return right;
- }
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "disallow unnecessary concatenation of literals or template literals",
- category: "Best Practices",
- recommended: false,
- url: "https://eslint.org/docs/rules/no-useless-concat"
- },
- schema: []
- },
- create(context) {
- const sourceCode = context.getSourceCode();
- return {
- BinaryExpression(node) {
-
- if (node.operator !== "+") {
- return;
- }
-
- const left = getLeft(node);
- const right = getRight(node);
- if (astUtils.isStringLiteral(left) &&
- astUtils.isStringLiteral(right) &&
- astUtils.isTokenOnSameLine(left, right)
- ) {
- const operatorToken = sourceCode.getFirstTokenBetween(left, right, isConcatOperatorToken);
- context.report({
- node,
- loc: operatorToken.loc.start,
- message: "Unexpected string concatenation of literals."
- });
- }
- }
- };
- }
- };
|