Skip to content

Instantly share code, notes, and snippets.

@brizandrew
Created July 11, 2017 21:59
Show Gist options
  • Save brizandrew/09360cdd8d65badc5dcdf1e6c6ce4619 to your computer and use it in GitHub Desktop.
Save brizandrew/09360cdd8d65badc5dcdf1e6c6ce4619 to your computer and use it in GitHub Desktop.
Renders a template string based on positional and keyword arguments.
/**
* Renders a template string based on positional and keyword arguments.
* Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
* @example
* // returns 'YAY!'
* let t1Closure = template`${0}${1}${0}!`;
* t1Closure('Y', 'A');
* @example
* // returns 'Hello World!'
* let t2Closure = template`${0} ${'foo'}!`;
* t2Closure('Hello', {foo: 'World'});
* @example
* // returns 'value'
* let t3Closure = template`${'foo.bar'}`;
* t3Closure({foo: { bar: 'value' } });
*/
function template(strings, ...keys) {
return ((...values) => {
let dict = values[values.length - 1] || {};
let result = [strings[0]];
keys.forEach((key, i) => {
let value;
if(Number.isInteger(key)){
value = values[key];
}
else{
let keyLayers = key.split('.');
value = dict;
for(kL of keyLayers){
value = value[kL];
}
}
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment