Skip to content

Instantly share code, notes, and snippets.

@cspotcode
Created June 17, 2019 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cspotcode/102dc6a7c81e3aafe14b863733ac9710 to your computer and use it in GitHub Desktop.
Save cspotcode/102dc6a7c81e3aafe14b863733ac9710 to your computer and use it in GitHub Desktop.
exec with tagged template literals
// TODO also support quoting?
function execTmpl(tmpl: TemplateStringsArray, ...rest: Array<string | Array<string>>) {
const delim = {};
const acc = [];
for(let i = 0; i < tmpl.length; i++) {
if(tmpl[i].length !== 0) {
const bits = tmpl[i].split(/ +/);
for(let j = 0; j < bits.length; j++) {
// whitespace becomes a delim
if(j) {
acc.push(delim);
}
acc.push(bits[j]);
}
}
if(rest.length > i) {
const bits = makeArray(rest[i]);
// append contents of interpolated item
for(let j = 0; j < bits.length; j++) {
// whitespace becomes a delim
if(j) {
acc.push(delim);
}
acc.push(bits[j]);
}
}
}
const args = [];
for(const item of acc) {
if(item === delim) {
acc.push('');
} else {
acc[acc.length - 1] = acc[acc.length - 1] + item;
}
}
return args;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment