Skip to content

Commit c6b3880

Browse files
committed
refactor: Extracted getBuffer()
1 parent 60f0f17 commit c6b3880

2 files changed

Lines changed: 15 additions & 18 deletions

File tree

src/parse/preprocess.ts

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { parse, type Range } from '../utils/content-tag.js';
1+
import { getBuffer, parse, type Range } from '../utils/content-tag.js';
22

33
export interface Template {
44
contents: string;
@@ -10,19 +10,8 @@ export interface Template {
1010
};
1111
}
1212

13-
const BufferMap: Map<string, Buffer> = new Map();
14-
1513
const PLACEHOLDER = '~';
1614

17-
function getBuffer(s: string): Buffer {
18-
let buf = BufferMap.get(s);
19-
if (!buf) {
20-
buf = Buffer.from(s);
21-
BufferMap.set(s, buf);
22-
}
23-
return buf;
24-
}
25-
2615
/** Slice string using byte range */
2716
function sliceByteRange(s: string, a: number, b?: number): string {
2817
const buf = getBuffer(s);
@@ -35,11 +24,6 @@ function byteToCharIndex(s: string, byteOffset: number): number {
3524
return buf.subarray(0, byteOffset).toString().length;
3625
}
3726

38-
/** Calculate byte length */
39-
function byteLength(s: string): number {
40-
return getBuffer(s).length;
41-
}
42-
4327
function replaceRange(
4428
s: string,
4529
start: number,
@@ -84,7 +68,7 @@ export function preprocessTemplateRange(
8468

8569
const tplLength = template.range.end - template.range.start;
8670
const spaces =
87-
tplLength - byteLength(content) - prefix.length - suffix.length;
71+
tplLength - getBuffer(content).length - prefix.length - suffix.length;
8872
const total = prefix + content + ' '.repeat(spaces) + suffix;
8973

9074
return replaceRange(code, template.range.start, template.range.end, total);

src/utils/content-tag.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,19 @@ type Range = {
1010
start: number;
1111
};
1212

13+
const BufferMap = new Map<string, Buffer>();
14+
15+
export function getBuffer(string_: string): Buffer {
16+
let buffer = BufferMap.get(string_);
17+
18+
if (!buffer) {
19+
buffer = Buffer.from(string_);
20+
BufferMap.set(string_, buffer);
21+
}
22+
23+
return buffer;
24+
}
25+
1326
export function parse(
1427
file: string,
1528
options?: PreprocessorOptions,

0 commit comments

Comments
 (0)