Skip to content

Instantly share code, notes, and snippets.

@jaames
Created June 7, 2021 23:05
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 jaames/af0cea637ac06423b03fa261475e6347 to your computer and use it in GitHub Desktop.
Save jaames/af0cea637ac06423b03fa261475e6347 to your computer and use it in GitHub Desktop.
Tiny Typescript string template compiler
// makes use of tagged template literals
const compileTemplate = (strings: TemplateStringsArray, ...expr: string[]) => {
return (replacements: Record<string, any>) => {
// convert ${'whatever'} instances to array of values
const values = expr.map(key => replacements[key] ?? key);
// rebuild string with replaced values
return strings.reduce((result, part, i) => result + part + (values[i] ?? ''), '');
}
}
// Usage
const template = compileTemplate`this is a ${'thing'}`;
const formatted = template({ thing: 'pen' });
// formatted === 'this is a pen'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment