Skip to content

Commit 5bc9a5d

Browse files
committed
perf: render template in a single pass
Replace the per-variable loop (each iteration building a fresh RegExp and scanning the full template) with one pass over TOKEN_REGEX that substitutes every token inline. Fewer allocations and O(n) in template length instead of O(n * number of variables). Unknown tokens are left untouched, matching the previous behavior.
1 parent 2d646c1 commit 5bc9a5d

1 file changed

Lines changed: 5 additions & 9 deletions

File tree

src/renderer.ts

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
1-
export function render(template: string, values: Record<string, string>): string {
2-
let result = template;
3-
4-
for (const [key, value] of Object.entries(values)) {
5-
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
6-
const pattern = new RegExp(`\\{\\{${escaped}\\}\\}`, 'g');
7-
result = result.replace(pattern, () => value);
8-
}
1+
const TOKEN_REGEX = /\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;
92

10-
return result;
3+
export function render(template: string, values: Record<string, string>): string {
4+
return template.replace(TOKEN_REGEX, (match, key) => (
5+
Object.hasOwn(values, key) ? values[key] : match
6+
));
117
}

0 commit comments

Comments
 (0)