Skip to content

Instantly share code, notes, and snippets.

@castarco
Created May 20, 2020 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save castarco/94c5385539cf4d7104cc4d3513c14f55 to your computer and use it in GitHub Desktop.
Save castarco/94c5385539cf4d7104cc4d3513c14f55 to your computer and use it in GitHub Desktop.
/**
* 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