Skip to content

Commit

Permalink
fix: improve fixer to cover more cases
Browse files Browse the repository at this point in the history
  • Loading branch information
snitin315 committed Nov 7, 2021
1 parent 054ae63 commit a0a5763
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/rules/prefer-template.js
Expand Up @@ -204,12 +204,21 @@ module.exports = {
const currentNodeText = sourceCode.getText(currentNode);

if (currentNode === currentNode.parent.left) {
if (isConcatenation(currentNode.right)) {
const openingParentesisSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "(");
const leftNodeText = currentNodeText.slice(0, openingParentesisSign.range[0] - firstToken.range[0]);

return `${leftNodeText}${currentNode.right.left.raw} + \`${escapeTemplatePlaceholders(currentNode.right.right.raw)}'`;
}

const leftNodeText = currentNodeText.slice(0, currentNode.right.range[0] - firstToken.range[0]);

return `${leftNodeText}\`${escapeTemplatePlaceholders(currentNode.right.raw)}'`;
}

if (currentNode.parent.left.right ? hasNonStringLiteral(currentNode.parent.left.right) : hasNonStringLiteral(currentNode.parent.left)) {
const nodeBeforeCurrentNode = currentNode.parent.left.right || currentNode.parent.left;

if (hasNonStringLiteral(nodeBeforeCurrentNode)) {
return `\\${escapeTemplatePlaceholders(firstToken.value)}\`${currentNodeText.slice(firstToken.value.length)}`;
}

Expand Down
10 changes: 10 additions & 0 deletions tests/lib/rules/prefer-template.js
Expand Up @@ -340,6 +340,16 @@ ruleTester.run("prefer-template", rule, {
output: "`${foo }\\`a\\`${ bar }\\`b\\`` + `\\`c\\`${ test}`",
errors
},
{
code: "'a' + ('b' + 'c') + d",
output: "'a' + 'b' + `c${ d}`",
errors
},
{
code: "'a' + ('`b`' + '`c`') + d",
output: "'a' + '`b`' + `\\`c\\`${ d}`",
errors
},
{
code: "var foo = \"Hello \" + \"world \" + \"another \" + test",
output: "var foo = \"Hello \" + \"world \" + `another ${ test}`",
Expand Down

0 comments on commit a0a5763

Please sign in to comment.