Skip to content

Instantly share code, notes, and snippets.

@giautm
Last active February 17, 2017 00:42
Show Gist options
  • Save giautm/743fde4fe42d21f4c46ca574a9d68c46 to your computer and use it in GitHub Desktop.
Save giautm/743fde4fe42d21f4c46ca574a9d68c46 to your computer and use it in GitHub Desktop.
const template = generateTemplateString("Xin chào ${map.name}, tuổi con ${age}.");
console.log(template({
name: 'None use',
age: 'chó',
map: {
name: 'Trần Minh Giàu',
}
}));
const generateTemplateString = (() => {
const cache = {};
return (template) => {
let func = cache[template];
if (func === undefined) {
// Replace ${expressions} (etc) with ${a.expressions}.
// Afterwards, replace anything that's not ${a.expressions}' (etc) with a blank string.
const sanitized = template
.replace(/\$\{([\s]*[^;\s\{]+[\s]*)\}/g, (_, match) => `\$\{a.${match.trim()}||''\}`)
.replace(/(\$\{(?!a\.)[^}]+\})/g, '');
func = new Function('a', `return \`${sanitized}\``);
}
return func;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment