Skip to content

Commit

Permalink
fix(perf): make template faster (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jun 27, 2024
1 parent 370a336 commit 8e4eb5e
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 8e4eb5e

Please sign in to comment.