Created
May 20, 2020 21:17
-
-
Save castarco/94c5385539cf4d7104cc4d3513c14f55 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* This approach has many limitations: | |
* - it does not accept variable names with numbers or other symbols (relatively easy to fix) | |
* - it does not accept arbitrary expressions (quite difficult to fix) | |
*/ | |
function deferredTemplateLiteral(template: string, env: { [key: string]: string | undefined }): string { | |
const varsMatcher = /\${([a-zA-Z_]+)}/ | |
const globalVarsmatcher = /\${[a-zA-Z_]+}/g | |
const varMatches: string[] = template.match(globalVarsmatcher) ?? [] | |
const templateVarNames = varMatches.map(v => v.match(varsMatcher)?.[1] ?? '') | |
const templateValues: (string | undefined)[] = templateVarNames.map(v => env[v]) | |
const templateInterpolator = new Function(...[...templateVarNames, `return \`${template}\`;`]) | |
return templateInterpolator(...templateValues) | |
} | |
// Usage: | |
deferredTemplateLiteral("hello ${thing}", {thing: "world"}) === "hello world" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment