Last active
February 17, 2017 00:42
-
-
Save giautm/743fde4fe42d21f4c46ca574a9d68c46 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', | |
} | |
})); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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