Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Print a 40-column receipt in JavaScript

95 A receipt padded into columns that actually line up

fair

Render that basket as a 40-character receipt: description on the left, quantity and amount right-aligned in fixed columns, a rule, and a total row. Every line must be exactly 40 characters. Then find the two ways this breaks — a description longer than its column, and an amount wider than its column — and a third that only shows up with an accented name.

Stuck? Three hints, smallest first
  1. 1. padEnd for the left column, padStart for the right ones. The argument is the finished width.
  2. 2. Padding never shortens anything, so a long value has to be cut deliberately: pad, then slice.
  3. 3. padEnd counts UTF-16 code units, not the characters you can see.

The answer

const WIDTH = 40;
const NAME_COL = 22;
const QTY_COL = 3;
const CASH_COL = 15;

const money = (kobo) => (kobo / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
const fit = (text, width) => (text.length <= width ? text.padEnd(width) : text.slice(0, width - 1) + '\u2026');
const row = (name, qty, kobo) => fit(name, NAME_COL) + String(qty).padStart(QTY_COL) + money(kobo).padStart(CASH_COL);
const rule = (char) => char.repeat(WIDTH);
const totalRow = (label, kobo) => fit(label, NAME_COL + QTY_COL) + money(kobo).padStart(CASH_COL);

const basket = [
  { name: 'Gari, 5kg', unitKobo: 450000, qty: 2 },
  { name: 'Palm oil, 1L', unitKobo: 285000, qty: 1 },
  { name: 'Sachet water (bag of 20 sachets)', unitKobo: 35000, qty: 3 },
];

const lines = basket.map((line) => row(line.name, line.qty, line.unitKobo * line.qty));
const subtotalKobo = basket.reduce((sum, line) => sum + line.unitKobo * line.qty, 0);
const vatKobo = Math.round((subtotalKobo * 750) / 10000);

const receipt = [
  fit('ADAURA STORES, IKEJA', WIDTH),
  rule('='),
  ...lines,
  rule('-'),
  totalRow('Subtotal', subtotalKobo),
  totalRow('VAT 7.5%', vatKobo),
  totalRow('TOTAL', subtotalKobo + vatKobo),
];

const everyLineIsExactlyWide = receipt.map((line) => line.length);
const longNameFitted = fit('Sachet water (bag of 20 sachets)', NAME_COL);
const decimalPointColumns = lines.map((line) => line.indexOf('.'));

// An amount too wide for its column pushes the row out instead of being cut.
const oversized = row('Generator, 5kVA', 1, 100000000000);

// padEnd counts code units, so a decomposed accent eats a column of padding.
const decomposed = 'Ad\u00e9yemi'.normalize('NFD');
const padded = decomposed.padEnd(10);
const composedPadded = decomposed.normalize('NFC').padEnd(10);

console.log(receipt.join('\n'));
console.log('oversized row length:', oversized.length, '<- pushed past 40');
console.log('padded NFD          :', padded.length, 'code units,', padded.replace(/\p{M}/gu, '').length, 'visible');

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.

8 checks

test('all nine lines of the receipt are exactly 40 characters', everyLineIsExactlyWide, [40, 40, 40, 40, 40, 40, 40, 40, 40]);
test('a description too long for its column is cut and ellipsised, to exactly the column width', [longNameFitted, longNameFitted.length], ['Sachet water (bag of \u2026', 22]);
test('so the decimal points land in the same column on every line', decimalPointColumns, [37, 37, 37]);
test('the total rows use the description and quantity columns together', totalRow('TOTAL', 1386750).length, 40);
test('padStart never truncates, so an amount wider than its column widens the row', [oversized.length, oversized.endsWith('1,000,000,000.00')], [41, true]);
test('padding counts code units: a decomposed accent leaves the column a character short', [padded.length, padded.replace(/\p{M}/gu, '').length], [10, 9]);
test('composing it first is the fix', [composedPadded.length, composedPadded.replace(/\p{M}/gu, '').length], [10, 10]);
test('and the two forms look identical while comparing as different strings', [decomposed === decomposed.normalize('NFC'), decomposed.normalize('NFC').length], [false, 7]);

The rule to internalise is that padStart and padEnd only ever add. Given a value already wider than the target they return it untouched, silently, which is how one long product name or one unexpectedly large amount destroys the alignment of a whole receipt. Fixed-width output therefore needs both operations: pad to the width, and slice to the width. The fifth assertion is that failure left in on purpose — a row 41 characters wide, because nothing cut the amount.

Cutting to width - 1 and appending an ellipsis keeps the column honest, and the third assertion is what the whole exercise is for: the decimal points all land in the same column, so the numbers can be read down the page. That is the actual product requirement, and it holds only because every line is built from the same three widths rather than from spaces typed by hand.

The last three assertions are the part that catches people out on real customer names. 'Adéyemi' can be seven code points with a precomposed é, or eight with a combining acute — the two render identically, compare as different strings, and pad to different visible widths, because padEnd counts code units and the combining mark is a unit that occupies no column. Normalising to NFC on the way in fixes the padding and the comparison at once. It still does not fix emoji or scripts with wide glyphs: a genuinely wide character occupies two terminal columns whatever length says, which is why monospaced output of arbitrary user text is harder than it looks.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.