Skip to content

Commit

Permalink
fix: improve prefer-template fixer
Browse files Browse the repository at this point in the history
Fixes #15083
  • Loading branch information
snitin315 committed Oct 28, 2021
1 parent a86ffc0 commit 9ee0532
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/rules/prefer-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,20 @@ function hasNonStringLiteral(node) {
return !astUtils.isStringLiteral(node);
}

/**
* Checks whether or not a given binary expression has an identifier reference.
* @param {ASTNode} node A node to check.
* @returns {boolean} `true` if the node has identifier reference.
*/
function hasIdentifierReference(node) {
if (isConcatenation(node)) {

// `left` is deeper than `right` normally.
return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left);
}
return node.type === "Identifier";
}

/**
* Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal.
* @param {ASTNode} node The node that will be fixed to a template literal
Expand Down Expand Up @@ -187,6 +201,14 @@ module.exports = {
return sourceCode.getText(currentNode);
}

if (isConcatenation(currentNode) && !hasIdentifierReference(currentNode)) {

// eslint-disable-next-line require-unicode-regexp -- `"Hello " + "World"` -> `Hello World`
const concatenatedText = sourceCode.getText(currentNode).split("+").map(e => e.trim()).join("").replace(/"/g, "");

return `\`${concatenatedText}\``;
}

if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+");
const textBeforePlus = getTextBetween(currentNode.left, plusSign);
Expand Down

0 comments on commit 9ee0532

Please sign in to comment.