Skip to content

Instantly share code, notes, and snippets.

@atomless
Last active November 14, 2018 12:43
Show Gist options
  • Save atomless/023e3dc2b31959702788a5b89fb0a9a1 to your computer and use it in GitHub Desktop.
Save atomless/023e3dc2b31959702788a5b89fb0a9a1 to your computer and use it in GitHub Desktop.
String To String Literal Template
/** Generate a string literal template with arbitrarily many substitutions.
* Usage: (IMPORTANT, MUST OMIT BRACKETS IN THE INSTANTIATION CALL):
* let template = stringLiteralTemplate`Hello, ${0}. This is a ${1}`;
* let final_string = template.with('world', 'test');
* >> "Hello, world. This is a test"
* Also:
* let template = stringLiteralTemplate`${0}, ${0}, ${1}. ${2}. ${2} 1, 2, 3.`;
* let final_string = template.with('Hello', 'World', 'Testing');
* >> "Hello, Hello, World. Testing. Testing 1, 2, 3"
*/
export const stringLiteralTemplate = (literals, ...substitutions) => ({
with() {
let out = [], i, k;
for (i = 0, k = 0; i < literals.length; i++) {
out[k++] = literals[i];
out[k++] = arguments[substitutions[i]];
}
out[k] = literals[i];
return out.join('');
}
}),
/**
* Convert a string into a string literal template.
* Usage:
* let template = toStringLiteralTemplate('Hello, ${0}. This is a ${1}`);
* let final_string = template.with('world', 'test');
* >> "Hello, world. This is a test"
*/
export const toStringLiteralTemplate = (str) => {
const arr = str.split(/\$\{\d+\}/g);
return stringLiteralTemplate(arr, ...(new Array(arr.length).fill(0).map((d,i) => i)));
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment