From 861d48dbf32aa08d6e582c7951fef4d4fb45f73d Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Wed, 13 Mar 2024 12:37:49 +0000 Subject: [PATCH] Transform snippets into a map in the browser for faster access --- packages/string-templates/src/helpers/javascript.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/string-templates/src/helpers/javascript.js b/packages/string-templates/src/helpers/javascript.js index 26c2753295..e38f9b5651 100644 --- a/packages/string-templates/src/helpers/javascript.js +++ b/packages/string-templates/src/helpers/javascript.js @@ -51,10 +51,16 @@ 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 + let snippetMap = {} + for (let snippet of context.snippets || []) { + snippetMap[snippet.name] = snippet.code + } + // Our $ context function gets a value from context. // We clone the context to avoid mutation in the binding affecting real // app context. - const clonedContext = cloneDeep(context) + const clonedContext = cloneDeep({ ...context, snippets: null }) const sandboxContext = { $: path => getContextValue(path, clonedContext), helpers: getJsHelperList(), @@ -64,9 +70,7 @@ module.exports.processJS = (handlebars, context) => { {}, { get: function (_, name) { - // This will error if the snippet doesn't exist, but that's intended - const snippet = (context.snippets || []).find(x => x.name === name) - return eval(iifeWrapper(snippet.code)) + return eval(iifeWrapper(snippetMap[name])) }, } ),