Skip to content

Commit 9449689

Browse files
committed
refactor: Extracted replaceContents()
1 parent 862c149 commit 9449689

2 files changed

Lines changed: 23 additions & 13 deletions

File tree

src/parse/preprocess.ts

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
getBuffer,
33
parse,
44
type Range,
5+
replaceContents,
56
sliceByteRange,
67
} from '../utils/content-tag.js';
78

@@ -17,15 +18,6 @@ export interface Template {
1718

1819
const PLACEHOLDER = '~';
1920

20-
function replaceRange(
21-
s: string,
22-
start: number,
23-
end: number,
24-
substitute: string,
25-
): string {
26-
return sliceByteRange(s, 0, start) + substitute + sliceByteRange(s, end);
27-
}
28-
2921
/**
3022
* Replace the template with a parsable placeholder that takes up the same
3123
* range.
@@ -57,14 +49,16 @@ export function preprocessTemplateRange(
5749

5850
// We need to replace forward slash with _something else_, because
5951
// forward slash breaks the parsed templates.
60-
const content = template.contents.replaceAll('/', PLACEHOLDER);
52+
const contents = template.contents.replaceAll('/', PLACEHOLDER);
6153

6254
const tplLength = template.range.end - template.range.start;
6355
const spaces =
64-
tplLength - getBuffer(content).length - prefix.length - suffix.length;
65-
const total = prefix + content + ' '.repeat(spaces) + suffix;
56+
tplLength - getBuffer(contents).length - prefix.length - suffix.length;
6657

67-
return replaceRange(code, template.range.start, template.range.end, total);
58+
return replaceContents(code, {
59+
contents: [prefix, contents, ' '.repeat(spaces), suffix].join(''),
60+
range: template.range,
61+
});
6862
}
6963

7064
/** Pre-processes the template info, parsing the template content to Glimmer AST. */

src/utils/content-tag.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,22 @@ export function parse(
3232
return preprocessor.parse(file, options);
3333
}
3434

35+
export function replaceContents(
36+
file: string,
37+
options: {
38+
contents: string;
39+
range: Range;
40+
},
41+
): string {
42+
const { contents, range } = options;
43+
44+
return [
45+
sliceByteRange(file, 0, range.start),
46+
contents,
47+
sliceByteRange(file, range.end),
48+
].join('');
49+
}
50+
3551
export function sliceByteRange(
3652
string_: string,
3753
indexStart: number,

0 commit comments

Comments
 (0)