From 1228e8bbb9c02d1e6cc6a2e9861bb945763013fe Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Wed, 26 Jun 2024 18:01:47 -0400 Subject: [PATCH] chore(perf): make `template` faster --- src/string/template.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/string/template.ts b/src/string/template.ts index a7f640ee..6b516b26 100644 --- a/src/string/template.ts +++ b/src/string/template.ts @@ -15,7 +15,12 @@ export function template( data: Record, 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) }