Created
March 29, 2024 06:27
-
-
Save ryanmorr/ffeb296b086fa6a16a4a00466e2da5bf to your computer and use it in GitHub Desktop.
Make a static template literal string come alive
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
function templit(tpl, tag) { | |
let exec; | |
return (data) => { | |
if (!exec) { | |
const vars = Object.getOwnPropertyNames(data).map((key) => `${key} = this['${key}']`); | |
exec = tag == null | |
? new Function(`var ${vars.join(',')}; return \`${tpl}\``) | |
: new Function('__tag', `var ${vars.join(',')}; return __tag\`${tpl}\``); | |
} | |
return tag == null ? exec.call(data) : exec.call(data, tag); | |
}; | |
} | |
// Usage: | |
// Create a template and execute it | |
const addition = templit('${a} + ${b} = ${a + b}'); | |
addition({a: 1, b: 2}); //=> "1 + 2 = 3" | |
// Use a tagged template function as an optional second argument | |
const status = templit('status: ${status}', (strings, ...values) => { | |
return strings.raw.reduce((acc, str) => acc + values.shift().toUpperCase() + str); | |
}); | |
status({status: 'ONLINE'}); //=> "message: HELLO WORLD" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment