Last active
September 10, 2019 21:41
-
-
Save ezirmusitua/c4d5a6b2ba8d80571c93e768a4cf278f to your computer and use it in GitHub Desktop.
[Template function] Simple template function using js template string #node #template
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
// 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