Skip to content

Commit 8ef6990

Browse files
committed
catch case when there is only single expr and optimize arrayToTree
1 parent 935cf04 commit 8ef6990

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

src/services/refactors/convertStringOrTemplateLiteral.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ namespace ts.refactor.convertStringOrTemplateLiteral {
7979

8080
if (head.text.length !== 0) arrayOfNodes.unshift(createStringLiteral(head.text));
8181

82-
const binaryExpression = arrayToTree(arrayOfNodes);
83-
return textChanges.ChangeTracker.with(context, t => t.replaceNode(context.file, templateLiteral, binaryExpression));
82+
const singleExpressionOrBinary = makeSingleExpressionOrBinary(arrayOfNodes);
83+
return textChanges.ChangeTracker.with(context, t => t.replaceNode(context.file, templateLiteral, singleExpressionOrBinary));
8484
}
8585
else {
8686
const stringLiteral = createStringLiteral(templateLiteral.text);
@@ -105,20 +105,24 @@ namespace ts.refactor.convertStringOrTemplateLiteral {
105105
return expr;
106106
}
107107

108-
function arrayToTree(nodes: ReadonlyArray<Expression>, accumulator?: BinaryExpression): BinaryExpression {
109-
if (nodes.length === 0) return accumulator!;
110-
111-
if (!accumulator) {
108+
function makeSingleExpressionOrBinary(nodes: ReadonlyArray<Expression>): Expression {
109+
if (nodes.length > 1) {
112110
const left = nodes[0];
113111
const right = nodes[1];
114112

115113
const binary = createBinary(left, SyntaxKind.PlusToken, right);
116-
return arrayToTree(nodes.slice(2), binary);
114+
return arrayToTree(nodes, 2, binary);
117115
}
118116

119-
const right = nodes[0];
117+
return nodes[0];
118+
}
119+
120+
function arrayToTree(nodes: ReadonlyArray<Expression>, index: number, accumulator: BinaryExpression): Expression {
121+
if (nodes.length === index) return accumulator;
122+
123+
const right = nodes[index];
120124
const binary = createBinary(accumulator, SyntaxKind.PlusToken, right);
121-
return arrayToTree(nodes.slice(1), binary);
125+
return arrayToTree(nodes, index + 1, binary);
122126
}
123127

124128
function isStringConcatenationValid(node: Node): boolean {
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/// <reference path='fourslash.ts' />
2+
3+
//// const foo = `/*x*/$/*y*/{42}`
4+
5+
goTo.select("x", "y");
6+
edit.applyRefactor({
7+
refactorName: "Convert string concatenation or template literal",
8+
actionName: "Convert to string concatenation",
9+
actionDescription: "Convert to string concatenation",
10+
newContent:
11+
`const foo = 42`,
12+
});
13+

0 commit comments

Comments
 (0)