Skip to content

Instantly share code, notes, and snippets.

@o0101
Last active July 24, 2020 12:39
Show Gist options
  • Save o0101/6d8a1b55f530a8efffd2806a75b705dc to your computer and use it in GitHub Desktop.
Save o0101/6d8a1b55f530a8efffd2806a75b705dc to your computer and use it in GitHub Desktop.
kinda smart
async function V(url, options, template, attachment, location = 'afterbegin', transformer = a => a) {
const s = transformer(await fetch(url, options).then(r => r.json()));
template = template.replace(/[^\\]{/g, '${'); // replace any unescaped { with ${
const h = await (new Function(`return Cook\`${template}\`;`)()); // print a template like `<a href={s.url}>{s.title}</a>`
if ( ! attachment ) return h; // can nest V functions
const e = attachment instanceof Element ? attachment : document.querySelector(attachment+'');
e.insertAdjacentHTML(h, location);
return e;
}
async function Cook(strings, ...vars) {
vars = await Promise.all(vars);
let result = '';
for( const s of strings ) {
result += s;
result += vars.shift();
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment