Tech »  Topic »  How to Add Auto Caching to Your JS Template Engine

How to Add Auto Caching to Your JS Template Engine


If you are looking at this you are probably wondering who I am.

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

compileToFunction

.

const compileToFunction = (template) => {
    return new Function("data", "return " + compileToString(template))
}

Now let's create a cache. We will use a 

Map

 for this.

const cache = new Map();

Now let's add a 

compile

 function ...


Copyright of this story solely belongs to hackernoon.com . To see the full text click HERE