In one of my articles I showed you how to create a simple JS template engine. In this article I will show you how to add simple caching to the compilation of our templates.
How Caching Works with JS Template Engines
Caching with our template engine is pretty simple. We just keep a key value object and use template strings as keys and functions as values. This will make subsequent uses of a template faster.
Implementing it inside Compile
All our compile function is this:
const compile = (template) => {
    return new Function("data", "return " + compileToString(template))
}Let's rename this to 
compileToFunctionconst compileToFunction = (template) => {
    return new Function("data", "return " + compileToString(template))
}Now let's create a cache. We will use a 
Mapconst cache = new Map();Now let's add a 
compilecacheAll we need to do is check if the 
cache.has(template)const compile = (template) => {
    if (cache.has(template)) {
        return cache.get(template);
    } else {
        const compiledFunction = compileToFunction(template);
        cache.set(template, compiledFunction);
        return compiledFunction;
    }
}
Changing Our Render Function
Currently our 
rendervar render = (template, data) => {
    return template.replace(/{{(.*?)}}/g, (match) => {
        return data[match.split(/{{|}}/).filter(Boolean)[0]]
    })
}I think we should change it to use 
compilecompiledataconst render = (template, data) => {
    return compile(template)(data);
}Conclusion
In this tutorial I showed how to extend the template engine we made in a previous post with caching for faster compilation and rendering.
Other Articles You Might Like
Also published here.
