Full round 3 of 5

Full round 3 of 5 Hard JavaScript

Checkout

A checkout in three files: some orders get free delivery they shouldn’t. Then a new coupon type, then one price call instead of one per line.

60:00

The real round is about an hour. Start the clock, do all four tasks out loud, and open an answer only when you’ve finished that task.

On this page

The handover

The interviewer

“This is checkout: checkout.js builds the bill, coupons.js knows the coupon codes, and catalog.js stands in for the pricing service (each call is a network round trip, so it counts them). Finance has flagged something.”

The code

Read all 3 files before anything else. For each one, say in a sentence what it does, then follow one request through them.

3 files

checkout.js

import { getPrice } from './catalog.js';
import { discountFor } from './coupons.js';

const FREE_DELIVERY_FROM = 49900; // free delivery from ₹499, counted after the coupon
const DELIVERY = 4000;

// The bill for a cart ([{ sku, qty }]) and an optional coupon code. Amounts in paise.
export async function bill(cart, code) {
  let subtotal = 0;
  for (const line of cart) subtotal += (await getPrice(line.sku)) * line.qty;
  const discount = discountFor(code, subtotal);
  const afterCoupon = subtotal - discount;
  const delivery = subtotal >= FREE_DELIVERY_FROM ? 0 : DELIVERY;
  return { subtotal, discount, delivery, total: afterCoupon + delivery };
}

coupons.js

// Coupon codes and what they take off. Amounts in paise.
const COUPONS = {
  SAVE50: { type: 'flat', amount: 5000 },
  TENOFF: { type: 'percent', percent: 10 },
};

export function discountFor(code, subtotal) {
  const c = COUPONS[code];
  if (!c) return 0;
  if (c.type === 'flat') return Math.min(c.amount, subtotal);
  return Math.round((subtotal * c.percent) / 100);
}

catalog.js

// A stand-in for the pricing service. It counts calls, because each one is a network round trip.
export const stats = { calls: 0 };

const PRICES = { tee: 39900, cap: 19900, mug: 24900, socks: 12900 };

export async function getPrice(sku) {
  stats.calls++;
  return PRICES[sku];
}

// Prices for many SKUs in one call.
export async function getPrices(skus) {
  stats.calls++;
  return Object.fromEntries(skus.map((s) => [s, PRICES[s]]));
}

Read every file first. After the report below, come back and click the line that causes it.

1Fix the bug

Bug report

Finance says some orders get free delivery they shouldn’t: the delivery rule is “free from ₹499, after the coupon”, but they see free delivery on orders that came to less than ₹499 once their coupon was applied.

Reproduce it

This example shows the report happening. Before reading on, work out why it prints what it does.

The example
import { bill } from './checkout.js';
// A ₹399 tee and ₹129 socks with the ₹50 coupon: ₹478 after the coupon.
const b = await bill([{ sku: 'tee', qty: 1 }, { sku: 'socks', qty: 1 }], 'SAVE50');
console.log('after coupon ' + (b.subtotal - b.discount) + ', delivery ' + b.delivery + ', total ' + b.total);

It prints

after coupon 47800, delivery 0, total 47800

It should print

after coupon 47800, delivery 4000, total 51800

Your hypothesis

Say it out loud, or write it here, before you hunt for the line: which file, what’s going wrong, and what you’d check to prove it.

It stays on this device.
Show the fix: the cause, the change and the test

The cause (checkout.js, line 13)

checkout.js line 13 decides delivery on subtotal, the amount before the coupon. The rule on line 4 counts after the coupon, so an order that only reaches ₹499 before its coupon still gets free delivery. Compare afterCoupon instead.

The fix

checkout.js

10  for (const line of cart) subtotal += (await getPrice(line.sku)) * line.qty;11  const discount = discountFor(code, subtotal);12  const afterCoupon = subtotal - discount;13  const delivery = subtotal >= FREE_DELIVERY_FROM ? 0 : DELIVERY;13  const delivery = afterCoupon >= FREE_DELIVERY_FROM ? 0 : DELIVERY;14  return { subtotal, discount, delivery, total: afterCoupon + delivery };15}

The test that proves it

It fails on the original code and passes once it’s fixed. Keep it, so the bug can’t come back.

import { bill } from './checkout.js';
const b = await bill([{ sku: 'tee', qty: 1 }, { sku: 'socks', qty: 1 }], 'SAVE50');
assert.equal(b.delivery, 4000);
assert.equal((await bill([{ sku: 'tee', qty: 2 }], 'SAVE50')).delivery, 0);

2Check the AI

The assistant in the side panel is allowed. Before you found the cause, you asked it about the report. Would you act on its answer?

You

Why do some orders under ₹499 get free delivery?

Assistant

You’re mixing rupees and paise: FREE_DELIVERY_FROM = 49900 means ₹49,900, not ₹499. Change it to 499 and the threshold will be right.

Show what’s wrong with its answer

Every amount in this code is in paise (the comment on line 7 says so, and the prices are like 39900), so 49900 is ₹499. Changing it to 499 would give almost every order free delivery: a much bigger bug. The assistant matched “big number, probably units” without reading the module. The real question is which amount the threshold is compared with.

3Add a feature

The interviewer

Marketing wants a capped coupon for the festival: FEST20 takes 20% off, but never more than ₹100. Add a coupon type for “percent off, up to a maximum”, and the FEST20 code.

Start from your fixed code. Say the feature back as a contract, ask about its edges, then build it with a test.

Show one way to build it

The approach

A new type, not a special case for one code: the next capped coupon should only need a line in the table. Work out the percentage first, then cap it.

The change

coupons.js

2const COUPONS = {3  SAVE50: { type: 'flat', amount: 5000 },4  TENOFF: { type: 'percent', percent: 10 },5  FEST20: { type: 'capped', percent: 20, max: 10000 },5};6 7export function discountFor(code, subtotal) {8  const c = COUPONS[code];9  if (!c) return 0;10  if (c.type === 'flat') return Math.min(c.amount, subtotal);11  return Math.round((subtotal * c.percent) / 100);12  const off = Math.round((subtotal * c.percent) / 100);13  return c.type === 'capped' ? Math.min(off, c.max) : off;12}

The test

It fails before the feature and passes after; the bug’s test still passes too.

import { discountFor } from './coupons.js';
assert.equal(discountFor('FEST20', 30000), 6000);
assert.equal(discountFor('FEST20', 90000), 10000);
assert.equal(discountFor('TENOFF', 30000), 3000);

4Make it faster

The interviewer

bill() calls the pricing service once per cart line, and each call is a network round trip: a 20-item cart makes 20 calls. The service has getPrices(skus). Price the whole cart in one call.

First count what it does too much of. Then change it without changing what it returns, and say what the change costs.

Show the speed-up and why it works

Why it’s slow, and the fix

The loop awaited one network call per line: N round trips, one after another. Asking for every distinct SKU at once makes it one call, and removing duplicates (the same item twice) keeps the request small. The maths stays the same.

The change

checkout.js

1import { getPrice } from './catalog.js';1import { getPrices } from './catalog.js';2import { discountFor } from './coupons.js';3 4const FREE_DELIVERY_FROM = 49900; // free delivery from ₹499, counted after the coupon⋯6 7// The bill for a cart ([{ sku, qty }]) and an optional coupon code. Amounts in paise.8export async function bill(cart, code) {9  const prices = await getPrices([...new Set(cart.map((line) => line.sku))]);9  let subtotal = 0;10  for (const line of cart) subtotal += (await getPrice(line.sku)) * line.qty;11  for (const line of cart) subtotal += prices[line.sku] * line.qty;11  const discount = discountFor(code, subtotal);12  const afterCoupon = subtotal - discount;13  const delivery = afterCoupon >= FREE_DELIVERY_FROM ? 0 : DELIVERY;

The test

It fails on the code before the speed-up and passes after. Every earlier test still passes, so the behaviour didn’t change.

import { bill } from './checkout.js';
import { stats } from './catalog.js';
const cart = ['tee', 'cap', 'mug', 'socks', 'tee'].map((sku) => ({ sku, qty: 1 }));
const b = await bill(cart, null);
assert.equal(stats.calls, 1);
assert.equal(b.subtotal, 39900 * 2 + 19900 + 24900 + 12900);

Sum it up

Score yourself

Tick what you really did. Interviewers score the process, so be honest: anything unticked is what to practise in the next round.

0 of 8

Your progress stays on this device.