JavaScriptFundamental (ES6), part 1
Tagged template literals in JavaScript
15 A tagged template
hardWrite a tag function that wraps every interpolated value in square brackets. Report how many text pieces arrive for how many values, and check whether the pieces object is the same on a second call from the same place in the source.
Stuck? Three hints, smallest first
- 1. A tag is called as
tag`text ${value} text`: the text pieces arrive as the first argument, the values as a rest parameter. - 2. There is always exactly one more piece than there are values, even when that means an empty string at one end.
- 3. The pieces array also carries
.raw, and it is cached per call site rather than rebuilt on each call.
function bracket(strings, ...values) {
return strings.reduce(
(out, part, i) => out + part + (i < values.length ? '[' + values[i] + ']' : ''),
''
);
}
const tagged = bracket`Total ${8200} for ${2} items`;
let captured;
const grab = (strings, ...values) => {
captured = { parts: [...strings], values, raw: typeof strings.raw };
return 'ignored';
};
grab`a${1}b${2}c`;
const siteOf = () => {
let seen;
const tag = (strings) => { seen = strings; return 0; };
tag`same site`;
return seen;
};
const adjacent = ((strings) => strings.length)`${1}${2}`;
const asObject = (strings, ...v) => ({ parts: strings.length, v });
console.log('bracket tag :', tagged);
console.log('captured :', captured);
console.log('adjacent holes:', adjacent, '<- three pieces, two of them empty');
console.log('same call site:', siteOf() === siteOf());
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the tag receives text and values separately', tagged, 'Total [8200] for [2] items');
test('there is always one more piece than value', captured.parts.length - captured.values.length, 1);
test('the pieces are the text between the holes', captured.parts, ['a', 'b', 'c']);
test('and the values are what the holes evaluated to', captured.values, [1, 2]);
test('adjacent holes leave an empty piece between them', adjacent, 3);
test('the pieces array also carries a raw copy', captured.raw, 'object');
test('it is cached per call site, so the same site hands back the same object', siteOf() === siteOf(), true);
test('a tag may return anything, not only a string', asObject`a${1}`, { parts: 2, v: [1] });
A tag intercepts the pieces before they are glued, which is the only way to do anything trustworthy with interpolated values: escape them for HTML, parameterise them into SQL, localise the text around them. Once a plain template has run there is no way left to tell which characters came from a hole.
The caching assertion is the part people miss. The pieces array is created once per call site and reused, so it is a legitimate cache key — a tag can memoise its compiled output against that object without hashing the strings.