From 95f71efdab75c8f8e6806d09a83131d3e3258d00 Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Wed, 13 Mar 2024 12:52:36 +0000 Subject: [PATCH] Cache snippet evaluations in the browser --- packages/string-templates/src/helpers/javascript.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/string-templates/src/helpers/javascript.js b/packages/string-templates/src/helpers/javascript.js index e38f9b5651..5be2619463 100644 --- a/packages/string-templates/src/helpers/javascript.js +++ b/packages/string-templates/src/helpers/javascript.js @@ -51,8 +51,10 @@ module.exports.processJS = (handlebars, context) => { // This is required to allow the final `return` statement to be valid. const js = iifeWrapper(atob(handlebars)) - // Transform snippets into an object for faster access + // Transform snippets into an object for faster access, and cache previously + // evaluated snippets let snippetMap = {} + let snippetCache = {} for (let snippet of context.snippets || []) { snippetMap[snippet.name] = snippet.code } @@ -70,7 +72,10 @@ module.exports.processJS = (handlebars, context) => { {}, { get: function (_, name) { - return eval(iifeWrapper(snippetMap[name])) + if (!(name in snippetCache)) { + snippetCache[name] = eval(iifeWrapper(snippetMap[name])) + } + return snippetCache[name] }, } ),