Created
June 7, 2021 23:05
-
-
Save jaames/af0cea637ac06423b03fa261475e6347 to your computer and use it in GitHub Desktop.
Tiny Typescript string template compiler
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
// 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