Skip to content

Commit

Permalink
chore(perf): make template faster
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jun 27, 2024
1 parent 370a336 commit cbcbb81
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/string/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@
export function template(
str: string,
data: Record<string, any>,
regex: RegExp = /\{\{(.+?)\}\}/g,
regex: RegExp = /\{\{(.+?)\}\}/g
): string {
return Array.from(str.matchAll(regex)).reduce((acc, match) => {
return acc.replace(match[0], data[match[1]])
}, str)
let result = "";
let from = 0;
let match: RegExpExecArray | null;
while ((match = regex.exec(str))) {
result += str.slice(from, match.index) + data[match[1]];
from = regex.lastIndex;
}
return result + str.slice(from);
}

0 comments on commit cbcbb81

Please sign in to comment.