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 1228e8b
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/string/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ export function template(
data: Record<string, any>,
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 1228e8b

Please sign in to comment.