pull/7539/head
Simon H 4 years ago committed by GitHub
parent 797438ba7e
commit 1e62e0b3b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -125,4 +125,3 @@ export default class Renderer {
}); });
} }
} }

@ -1,37 +1,30 @@
import { TemplateLiteral } from 'estree'; import { TemplateLiteral } from 'estree';
import { escape_template } from './stringify'; import { escape_template } from './stringify';
// Collapse string literals together /**
* Collapse string literals together
*/
export function collapse_template_literal(literal: TemplateLiteral) { export function collapse_template_literal(literal: TemplateLiteral) {
if (literal.quasis.length) { const collapsed_quasis = [];
// flatMap() to produce an array containing [quasi, expr, quasi, expr, ..., quasi] const collapsed_expressions = [];
const zip = literal.quasis.reduce((acc, cur, index) => {
const expr = literal.expressions[index]; let cur_quasi = literal.quasis[0];
acc.push(cur);
if (expr) {
acc.push(expr);
}
return acc;
}, []);
// An expression always follows a quasi and vice versa, ending with a quasi
for (let i = 0; i < literal.quasis.length; i++) {
const expr = literal.expressions[i];
const next_quasi = literal.quasis[i + 1];
// If an expression is a simple string literal, combine it with its preceding // If an expression is a simple string literal, combine it with its preceding
// and following quasi // and following quasi
let cur_quasi = zip[0]; if (next_quasi && expr.type === 'Literal' && typeof expr.value === 'string') {
const new_zip = [cur_quasi];
for (let i = 1; i < zip.length; i += 2) {
const expr = zip[i];
const next_quasi = zip[i + 1];
if (expr.type === 'Literal' && typeof expr.value === 'string') {
cur_quasi.value.raw += escape_template(expr.value) + next_quasi.value.raw; cur_quasi.value.raw += escape_template(expr.value) + next_quasi.value.raw;
} else { } else {
new_zip.push(expr); collapsed_expressions.push(expr);
new_zip.push(next_quasi); collapsed_quasis.push(next_quasi);
cur_quasi = next_quasi; cur_quasi = next_quasi;
} }
} }
// Reconstitute the quasi and expressions arrays literal.quasis = collapsed_quasis;
literal.quasis = new_zip.filter((_, index) => index % 2 === 0); literal.expressions = collapsed_expressions;
literal.expressions = new_zip.filter((_, index) => index % 2 === 1);
}
} }

Loading…
Cancel
Save