Skip to content

Instantly share code, notes, and snippets.

@klintmane
Forked from ebidel/es6-meta-programming.js
Created May 23, 2018 13:02
Show Gist options
  • Save klintmane/91c9c0f58b6d08e80d7700384100fe0f to your computer and use it in GitHub Desktop.
Save klintmane/91c9c0f58b6d08e80d7700384100fe0f to your computer and use it in GitHub Desktop.
"ES6 meta programming" using tagged template strings
// ES6 meta programming ???
// The more complex form of ES6 template strings are called
// "tagged" template strings. In short, they allow you to
// pass the final evaluated string to a function for further
// processing. This allows for some interesting things. For example:
//
// get`https://api.github.com/repos/${org}/${repo}/issues?sort=${sort}`;
//
// _could_ make a network request and return a Promise with the result
// (instead of a string).
//
// Why would you want to do this? Well, you wouldn't! Users won't expect
// such side effects and returning a value other than a string is...bananas.
//
// That said, this type of ES6 magic is a fun POC :)
// Run this in Babel: https://goo.gl/NfgPq1
function get(strs, ...values) {
// Reconstruct the final URL. If no substitutions were given,
// the original string is used.
let url = values.reduce((prev, curr, i) => prev + curr + strs.raw[i + 1], strs.raw[0]);
return fetch(url).then(response => response.json()).then(results => {
results.forEach(r => {
console.log(r.url, r.title);
});
return results;
});
}
let org = 'Polymer';
let repo = 'polymer';
let sort = 'updated';
// Example 1
get`https://api.github.com/repos/${org}/${repo}/issues?sort=${sort}`;
// Example 2
// Note: we dropped the Promise on the floor in Example 1.
// get`https://www.chromestatus.com/features.json`.then(results => {
// results.forEach(r => console.log(r.name));
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment