Skip to content

Instantly share code, notes, and snippets.

@bryanerayner
Last active April 10, 2021 14:14
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save bryanerayner/68e1498d4b1b09a30ef6 to your computer and use it in GitHub Desktop.
Save bryanerayner/68e1498d4b1b09a30ef6 to your computer and use it in GitHub Desktop.
/**
* Produces a function which uses template strings to do simple interpolation from objects.
*
* Usage:
* var makeMeKing = generateTemplateString('${name} is now the king of ${country}!');
*
* console.log(makeMeKing({ name: 'Bryan', country: 'Scotland'}));
* // Logs 'Bryan is now the king of Scotland!'
*/
var generateTemplateString = (function(){
var cache = {};
function generateTemplate(template){
var fn = cache[template];
if (!fn){
// Replace ${expressions} (etc) with ${map.expressions}.
var sanitized = template
.replace(/\$\{([\s]*[^;\s\{]+[\s]*)\}/g, function(_, match){
return `\$\{map.${match.trim()}\}`;
})
// Afterwards, replace anything that's not ${map.expressions}' (etc) with a blank string.
.replace(/(\$\{(?!map\.)[^}]+\})/g, '');
fn = Function('map', `return \`${sanitized}\``);
}
return fn;
};
return generateTemplate;
})();
@bryanerayner
Copy link
Author

Fixed. Thanks for the help.

@smeijer
Copy link

smeijer commented Nov 10, 2016

It seems to me that cache is being checked, but never assigned to? Perhaps add cache[template] = fn on line 29.

@smeijer
Copy link

smeijer commented Nov 10, 2016

I've modified your gist to support cache, and rewritten it to an es6 module. See the performance gain on jsPerf.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment