Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Validate and price an order end to end in JavaScript

140 one order, end to end

hard

Put the section together. Validate an order against a frozen tariff table collecting every problem at once, price it with a free-delivery threshold, format the money by hand with a grouping regular expression, and lay out a fixed-width receipt. Return a tagged result so a rejected order carries errors and never carries a total.

Stuck? Three hints, smallest first
  1. 1. For the checks, build an array of either a message or false and filter(Boolean). Line-level checks come from a map spread into the same array.
  2. 2. The result is a union: { ok: false, errors } or { ok: true, ...priced }. Nothing in between, so no caller can read half a total.
  3. 3. \B(?=(\d{3})+(?!\d)) matches every position that needs a comma: inside the string, with a multiple of three digits to its right and no digit after them.

The answer

const TARIFF = Object.freeze({ Ikeja: 120000, Yaba: 90000, Ketu: 150000 });
const FREE_ABOVE = 1500000;
const WIDTH = 30;

const money = (kobo) =>
  `₦${(kobo / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;

const problemsWith = (order) => [
  !order.customer?.trim() && 'customer is required',
  !Object.hasOwn(TARIFF, order.zone) && `no delivery to ${order.zone}`,
  !(order.lines?.length > 0) && 'an order needs at least one line',
  ...(order.lines ?? []).map((line, i) => line.qty > 0 ? false : `line ${i} needs a quantity`),
].filter(Boolean);

const priceUp = (order) => {
  const lines = order.lines.map((line) => ({ ...line, kobo: line.qty * line.unitKobo }));
  const goods = lines.reduce((sum, line) => sum + line.kobo, 0);
  const delivery = goods >= FREE_ABOVE ? 0 : TARIFF[order.zone];
  return { lines, goods, delivery, total: goods + delivery };
};

const row = (label, value) => label.padEnd(WIDTH - value.length, ' ') + value;
const receiptFor = (priced) => [
  ...priced.lines.map((line) => row(`${line.qty} x ${line.item}`, money(line.kobo))),
  row('Delivery', money(priced.delivery)),
  row('TOTAL', money(priced.total)),
];

const place = (order) => {
  const problems = problemsWith(order);
  return problems.length
    ? { ok: false, status: 'rejected', errors: problems }
    : { ok: true, status: 'accepted', ...priceUp(order) };
};

const smallOrder = {
  customer: 'Ngozi Okafor',
  zone: 'Yaba',
  lines: [
    { item: 'Garri, 5kg', qty: 2, unitKobo: 450000 },
    { item: 'Palm oil, 1L', qty: 1, unitKobo: 320000 },
  ],
};
const bulkOrder = {
  customer: 'Musa Bello',
  zone: 'Ketu',
  lines: [{ item: 'Rice, 50kg', qty: 1, unitKobo: 7500000 }],
};
const brokenOrder = { customer: '   ', zone: 'Abuja', lines: [{ item: 'Ice', qty: 0, unitKobo: 100 }] };

const small = place(smallOrder);
const bulk = place(bulkOrder);
const rejected = place(brokenOrder);
const receipt = receiptFor(small);

let frozenWrite = 'no error';
try { TARIFF.Yaba = 1; } catch (e) { frozenWrite = e.constructor.name; }

console.log(receipt.join('\n'));
console.log('bulk    :', bulk.status, money(bulk.total), '| delivery:', money(bulk.delivery));
console.log('rejected:', rejected.errors);

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.

9 checks

test('a good order is accepted and priced, delivery included', [small.status, small.goods, small.delivery, small.total], ['accepted', 1220000, 90000, 1310000]);
test('over the threshold the delivery is waived', [bulk.delivery, bulk.total], [0, 7500000]);
test('the money helper groups thousands and always shows kobo', [money(1310000), money(0), money(95000)], ['₦13,100.00', '₦0.00', '₦950.00']);
test('every receipt line is exactly one width', [...new Set(receipt.map((l) => l.length))], [30]);
test('with the amount flush right against the label', receipt[0], '2 x Garri, 5kg       ₦9,000.00');
test('the total row closes it out', receipt.at(-1), 'TOTAL               ₦13,100.00');
test('a broken order reports all three problems in one pass', rejected.errors, ['customer is required', 'no delivery to Abuja', 'line 0 needs a quantity']);
test('and carries no total at all, so nothing can read half an answer', [rejected.ok, Object.hasOwn(rejected, 'total')], [false, false]);
test('the tariff table is frozen, so a stray write throws instead of repricing', frozenWrite, 'TypeError');

Nothing here is new; the point is that the pieces fit. Validation collects rather than throwing, so a rejected order comes back with every problem at once. Pricing is a pure function of the order and the table, so it can be tested without a receipt. Formatting happens last, on integers that were kobo the whole way through. Each stage has one job and hands a plain object to the next.

The filter(Boolean) trick is worth keeping: an array of either a message or false, with line-level checks spread in from a map, gives you a flat list of problems with no push and no accumulator. Watch the one hazard — a legitimate empty-string message would be filtered out too, so keep the messages non-empty.

The tagged result is the design decision that matters most. { ok: false, errors } has no total property at all, so there is no path where a caller reads a price from a rejected order; the type of the answer tells you which fields exist. Combined with the frozen tariff table — where a stray write throws under strict mode instead of quietly repricing everything after it — the whole flow either produces a complete, correct order or produces a list of reasons why it did not.

Newsletter

New writing, when it lands.

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