JavaScriptFundamental (ES6), part 1
Format a fixed-width receipt in JavaScript
138 a receipt aligned with padStart and padEnd
fairPrint a fixed-width receipt: a centred shop name, a line per item with the amount flush right, rules made of repeated characters, and a zero-padded receipt number. Centre with padStart followed by padEnd. Then find the two ways padding lets you down — a label already wider than the column, and two strings that look identical but pad differently.
Stuck? Three hints, smallest first
- 1. Flush right in a fixed column is
label.padEnd(WIDTH - amount.length, '.') + amount. - 2. To centre, pad the front to half the leftover and then pad the end to the full width.
- 3.
padStartnever truncates: if the string is already long enough it comes back untouched, and your column overflows.
const WIDTH = 34;
const money = (kobo) => (kobo / 100).toFixed(2);
const row = (label, value) => label.padEnd(WIDTH - value.length, '.') + value;
const centred = (text) => text.padStart(Math.floor((WIDTH + text.length) / 2)).padEnd(WIDTH);
const qty = (n) => String(n).padStart(3);
const items = [
{ name: 'Garri, 5kg', count: 2, kobo: 450000 },
{ name: 'Palm oil, 1L', count: 1, kobo: 320000 },
{ name: 'Titus sardine', count: 3, kobo: 95000 },
];
const total = items.reduce((sum, i) => sum + i.count * i.kobo, 0);
const cash = 2000000;
const receipt = [
centred('BALOGUN STORES'),
centred(`Receipt ${String(7).padStart(6, '0')}`),
'='.repeat(WIDTH),
...items.map((i) => row(`${qty(i.count)} x ${i.name}`, money(i.count * i.kobo))),
'-'.repeat(WIDTH),
row('TOTAL', money(total)),
row('CASH', money(cash)),
row('CHANGE', money(cash - total)),
'='.repeat(WIDTH),
];
const widths = [...new Set(receipt.map((line) => line.length))];
const overflowing = row('Imported basmati rice, 50kg sack', money(total));
const precomposed = 'Adé';
const decomposed = 'Adé';
const dots = [precomposed, decomposed, decomposed.normalize('NFC')]
.map((s) => s.padStart(6, '.').split('.').length - 1);
console.log(receipt.join('\n'));
console.log('overflow:', overflowing.length, 'characters, not', WIDTH);
console.log('dots :', dots);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every line comes out exactly one width', widths, [34]);
test('the shop name sits centred, ten spaces each side', [receipt[0].indexOf('B'), receipt[0].length], [10, 34]);
test('the receipt number is zero padded to six', receipt[1].trim(), 'Receipt 000007');
test('an item row has the count left, the name next and the amount flush right', receipt[3], ' 2 x Garri, 5kg...........9000.00');
test('and the money column lines up because every amount has two decimals', [money(total), money(cash - total)], ['15050.00', '4950.00']);
test('a pad character can be more than one character, repeated then cut', ['5'.padStart(4, 'ab'), 'x'.padEnd(5, '-=')], ['aba5', 'x-=-=']);
test('padding never truncates, so an over-long label breaks the column', overflowing.length > WIDTH, true);
test('two strings that look the same pad differently: one has a combining mark', dots, [3, 2, 3]);
test('which normalise fixes, and only because both are three code units after it', [precomposed.length, decomposed.length, decomposed.normalize('NFC').length], [3, 4, 3]);
padStart and padEnd are what monospaced output is made of: a receipt, a console table, an invoice for a thermal printer. The pair used together is the centring idiom — pad the front to half the total, then pad the end to the whole width — and the fill argument can be any string, repeated and then cut to length, which is where the dotted leader in each row comes from.
Neither method truncates. That is the first failure: a label wider than its column is returned unchanged and the row silently runs long, taking the alignment of everything below it with it. If a label can be long, slice it before you pad it.
The second failure is the interesting one. Padding counts UTF-16 code units, not the marks a reader sees. Adé written with a precomposed é is three units; written as e plus a combining acute it is four, so it receives one fewer dot and the column bends by a character. Emoji and many scripts make this worse, since a single visible glyph can be two units or more. normalize('NFC') fixes the combining-mark case, which is worth doing on any name that arrives from a form; for genuinely wide characters, no amount of padding will align a proportional column and the answer is a real table.