Skip to content

Commit aa860e2

Browse files
committed
refactor: Simplified traverse() method
1 parent ed2566d commit aa860e2

1 file changed

Lines changed: 26 additions & 23 deletions

File tree

src/parse/index.ts

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -30,29 +30,34 @@ function convertNode(
3030

3131
/** Traverses the AST and replaces the transformed template parts with other AST */
3232
function convertAst(ast: File, templates: Template[]): void {
33-
const unprocessedTemplates = [...templates];
34-
3533
traverse(ast, {
3634
enter(path) {
3735
const { node } = path;
38-
if (
39-
node.type === 'BlockStatement' ||
40-
node.type === 'ObjectExpression' ||
41-
node.type === 'StaticBlock'
42-
) {
43-
const { range } = node;
44-
assert('expected range', range);
45-
const [start, end] = range;
36+
// eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
37+
switch (node.type) {
38+
case 'BlockStatement':
39+
case 'ObjectExpression':
40+
case 'StaticBlock': {
41+
assert('expected range', node.range);
42+
const [start, end] = node.range;
43+
44+
const templateIndex = templates.findIndex((template) => {
45+
const { utf16Range } = template;
46+
47+
if (utf16Range.start === start && utf16Range.end === end) {
48+
return true;
49+
}
4650

47-
const templateIndex = unprocessedTemplates.findIndex(
48-
(t) =>
49-
(t.utf16Range.start === start && t.utf16Range.end === end) ||
50-
(node.type === 'ObjectExpression' &&
51-
t.utf16Range.start === start - 1 &&
52-
t.utf16Range.end === end + 1),
53-
);
54-
if (templateIndex > -1) {
55-
const rawTemplate = unprocessedTemplates.splice(templateIndex, 1)[0];
51+
return (
52+
node.type === 'ObjectExpression' &&
53+
utf16Range.start === start - 1 &&
54+
utf16Range.end === end + 1
55+
);
56+
});
57+
if (templateIndex === -1) {
58+
return null;
59+
}
60+
const rawTemplate = templates.splice(templateIndex, 1)[0];
5661
if (!rawTemplate) {
5762
throw new Error(
5863
'expected raw template because splice index came from findIndex',
@@ -65,18 +70,16 @@ function convertAst(ast: File, templates: Template[]): void {
6570
ast.comments.splice(index, 1);
6671
}
6772
convertNode(node, rawTemplate);
68-
} else {
69-
return null;
7073
}
7174
}
7275

7376
return null;
7477
},
7578
});
7679

77-
if (unprocessedTemplates.length > 0) {
80+
if (templates.length > 0) {
7881
throw new Error(
79-
`failed to process all templates, ${unprocessedTemplates.length} remaining`,
82+
`failed to process all templates, ${templates.length} remaining`,
8083
);
8184
}
8285
}

0 commit comments

Comments
 (0)