JavaScriptFundamental (ES6), part 1
Tagged templates and String.raw in JavaScript
76 A tagged template for a receipt, and String.raw
fairWrite a tag function that formats every interpolated number as naira and leaves the text between untouched. Prove the shape of what a tag receives, then use String.raw to keep a backslash as a backslash, and look at what raw holds when the escape sequence was not even valid.
Stuck? Three hints, smallest first
- 1. A tag is called as
tag(strings, ...values), andstrings.lengthis alwaysvalues.length + 1. - 2.
strings.rawis the same list before escape sequences were processed. - 3. In a tagged template an invalid escape is allowed: the cooked string becomes
undefinedand onlyrawsurvives.
const money = (strings, ...values) =>
strings.reduce((out, part, i) => {
const value = values[i];
const shown =
i >= values.length ? '' : typeof value === 'number' ? `₦${(value / 100).toFixed(2)}` : String(value);
return out + part + shown;
}, '');
const buyer = 'Adaeze';
const kobo = 45000;
const qty = 3;
const bags = `${qty} bags`;
const receipt = money`${buyer} takes ${bags} and pays ${kobo * qty}`;
const noHoles = money`nothing to fill`;
const shape = (strings, ...values) => ({
parts: [...strings],
values,
counts: [strings.length, values.length],
frozen: Object.isFrozen(strings),
});
const inspected = shape`a${1}b${2}c`;
const edges = shape`${'first'}middle${'last'}`;
const rawText = String.raw`line\nbreak`;
const cookedText = `line\nbreak`;
const fifthChar = [rawText.charCodeAt(4), cookedText.charCodeAt(4)];
const peek = (strings) => [strings[0], strings.raw[0]];
const invalid = peek`\unit`;
const pattern = new RegExp(String.raw`\d{4}-\d{2}`);
const matched = pattern.test('2019-05');
console.log('receipt:', receipt);
console.log('shape :', inspected);
console.log('edges :', edges.parts, edges.values);
console.log('raw :', rawText, '| lengths:', rawText.length, cookedText.length);
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 decides how each interpolated value is rendered, by type', receipt, 'Adaeze takes 3 bags and pays ₦1350.00');
test('a template with no holes still arrives as one string and no values', [noHoles, shape`x`.counts], ['nothing to fill', [1, 0]]);
test('there is always one more string than there are values', [inspected.parts, inspected.values, inspected.counts], [['a', 'b', 'c'], [1, 2], [3, 2]]);
test('so a hole at either end shows up as an empty string', [edges.parts, edges.values], [['', 'middle', ''], ['first', 'last']]);
test('the strings array is frozen, so a tag cannot rewrite its own input', inspected.frozen, true);
test('String.raw keeps the backslash; a normal template turns it into a newline', fifthChar, [92, 10]);
test('which is why it is the honest way to write a regular expression', [matched, pattern.source.length], [true, 11]);
test('an invalid escape has no cooked form at all, only a raw one', [invalid[0] === undefined, invalid[1].charCodeAt(0), invalid[1].length], [true, 92, 5]);
A tagged template hands the tag the literal text and the interpolated values separately, and that separation is the whole point. The tag can format values, escape them, count them or ignore them, and it always knows which parts of the string the author wrote and which came from data. Every safe-HTML and safe-SQL template helper is built on exactly that distinction.
The shape is fixed: one more string than values, empty strings at the ends when a hole starts or finishes the template, and the array is frozen so a tag cannot mutate what it was handed. strings.raw carries the same text before escapes were processed, which is what String.raw returns wholesale — the reason a Windows path or a regular expression source is far more readable through it than through a wall of doubled backslashes.
The last assertion is the odd corner. Inside a tagged template an invalid escape sequence is no longer a syntax error: the cooked entry becomes undefined and the raw entry keeps the characters you typed. So a tag that reads strings[i] can receive undefined from perfectly deliberate input, and a tag meant for path-like or regex-like text should read strings.raw instead.