Skip to content

Instantly share code, notes, and snippets.

@aleph-naught2tog
Created April 30, 2019 00:36
Show Gist options
  • Save aleph-naught2tog/810630cbe3cbaa9a00cf6541150e6008 to your computer and use it in GitHub Desktop.
Save aleph-naught2tog/810630cbe3cbaa9a00cf6541150e6008 to your computer and use it in GitHub Desktop.
Template tags
/*
Some languages, like Elixir, have sigils -- things that often look like a ~, a letter, and then some delimiters
with a string between them.
One handy one is: `~w` -- in Elixir, you can look it up in the Kernel as `sigil_w`.
*/
// this is a one-liner of the function in the earlier file
const basicTag = (slots, ...values) => slots.map((slot, index) => [slot, values[index]].join('')).join('');
function w(pieces, ...values) {
return basicTag(pieces, ...values).split(/\s/);
}
const letters = w`a b c d e f g h`; // => ["a", "b", "c", "d", "e", "f", "g", "h"]
const firstMessage = w`hello world`; // => ["hello", "world"]
/*
Tagged template literals are functions that you call as if you're using a template string.
They look like a function call -- and are, in fact -- only instead of parentheses, you use backticks.
*/
/*
This next function does nothing but interpolate the string.
`.join('')` joins the pieces together as a string,
with nothing between the pieces. So, ['a','b'].join('') is 'ab', etc.
It's your simplest template string.
*/
function basicTag(stringPieces, ...interpolatedValues) {
return stringPieces.map((piece, index) => {
const maybeValue = interpolatedValues[index];
// if maybeValue is undefined, this becomes just `piece`
return [piece, maybeValue].join('');
}).join('');
}
const ninetyNineApples = basicTag`${99} apples`; // "99 apples"
const alsoNinetyNineApples = basicTag(['',' apples'], 99); // "99 apples"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment