Skip to content

Instantly share code, notes, and snippets.

@ezirmusitua
Last active September 10, 2019 21:41
Show Gist options
  • Save ezirmusitua/c4d5a6b2ba8d80571c93e768a4cf278f to your computer and use it in GitHub Desktop.
Save ezirmusitua/c4d5a6b2ba8d80571c93e768a4cf278f to your computer and use it in GitHub Desktop.
[Template function] Simple template function using js template string #node #template
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
function template(strings, ...keys) {
return ((...values) => {
const dict = values[values.length - 1] || {};
const result = [strings[0]];
keys.forEach((key, i) => {
const value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
const t1Closure = template`${0}${1}${0}!`;
t1Closure('Y', 'A'); // "YAY!"
const t2Closure = template`${0} ${'foo'}!`;
t2Closure('Hello', {foo: 'World'}); // "Hello World!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment