JavaScriptFundamental (ES6), part 1
Multi-line template literals and dedent in JavaScript
13 Multi-line templates and a dedent helper
fairWrite a three-line receipt as one template literal. Then notice that source indentation ends up inside the string, and write dedent to strip the common leading whitespace.
Stuck? Three hints, smallest first
- 1. A newline inside backticks is a real newline in the string. No
\nneeded. - 2. That means the indentation of your source code is part of the value.
- 3. For dedent: drop the leading and trailing blank lines, find the smallest indent across the non-blank lines, then slice that many characters off each.
const receipt = `Ikeja branch
Total: 8200
Thank you`;
const lines = receipt.split('\n');
const indented = () => {
return `
one
two
`;
};
const dedent = (text) => {
const rows = text.replace(/^\n/, '').replace(/\n\s*$/, '').split('\n');
const widths = rows.filter((r) => r.trim() !== '').map((r) => r.length - r.trimStart().length);
const pad = Math.min(...widths);
return rows.map((r) => r.slice(pad)).join('\n');
};
console.log('lines :', lines);
console.log('raw indented :', JSON.stringify(indented()));
console.log('dedented :', JSON.stringify(dedent(indented())));
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a template keeps its newlines', lines.length, 3);
test('the first line', lines[0], 'Ikeja branch');
test('the last line', lines[2], 'Thank you');
test('the newline is one real character', receipt.includes('\n'), true);
test('source indentation lands in the string', indented().split('\n')[1], ' one');
test('which is why a dedent helper exists', dedent(indented()), 'one\ntwo');
test('a single-line template has no newline at all', `plain`.includes('\n'), false);
Multi-line templates are what killed 'line one\n' + 'line two\n', and they brought one problem with them: whatever indentation makes the source readable is also in the value. For a log line nobody cares; for generated code or a test fixture it matters, so a four-line dedent is worth keeping around.
Math.min(...widths) is the whole trick. The common indent is the smallest one, and blank lines have to be excluded or they would drag it to zero.