Full round 1 of 5

Full round 1 of 5 Easy JavaScript

Order history

An orders API in three files: the newest orders are missing, then a filter to add and a query to cut.

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 the order-history API: ordersRoute.js handles GET /orders, orderService.js does the paging, and db.js stands in for the database (it counts queries). Customers are complaining, can you take a look?”

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

ordersRoute.js

import { listOrders } from './orderService.js';

// GET /orders?page=1&limit=3 for the signed-in customer.
export async function getOrders(req) {
  const page = Number(req.query.page ?? 1);
  const limit = Number(req.query.limit ?? 3);
  if (!Number.isInteger(page) || page < 1) return { status: 400, body: { error: 'page must be 1 or more' } };
  if (!Number.isInteger(limit) || limit < 1 || limit > 50) return { status: 400, body: { error: 'limit must be 1 to 50' } };
  const body = await listOrders(req.user, page, limit);
  return { status: 200, body };
}

orderService.js

import { countOrders, findOrders } from './db.js';

// One page of a customer's orders, newest first. Pages start at 1.
export async function listOrders(customer, page, limit) {
  const offset = page * limit;
  const orders = await findOrders({ customer }, { offset, limit });
  const total = await countOrders({ customer });
  return { orders, page, hasMore: offset + orders.length < total };
}

db.js

// A stand-in for the orders table. It counts queries, so you can see how many a request makes.
export const stats = { queries: 0 };

const ORDERS = [];
for (let id = 1; id <= 7; id++) {
  ORDERS.push({ id, customer: 'asha', total: id * 100, status: id % 3 === 0 ? 'cancelled' : 'delivered' });
}

const matches = (where) => (o) => Object.entries(where).every(([k, v]) => o[k] === v);

// The rows that match where, newest first.
export async function findOrders(where, { offset = 0, limit = Infinity } = {}) {
  stats.queries++;
  return ORDERS.filter(matches(where)).sort((a, b) => b.id - a.id).slice(offset, offset + limit);
}

export async function countOrders(where) {
  stats.queries++;
  return ORDERS.filter(matches(where)).length;
}

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

1Fix the bug

Bug report

Customers say their most recent orders are missing from Order history, and the last page is often empty. The order count on the account page is right.

Reproduce it

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

The example
import { getOrders } from './ordersRoute.js';
for (const page of [1, 2, 3]) {
  const res = await getOrders({ user: 'asha', query: { page, limit: 3 } });
  console.log('page ' + page + ': ' + (res.body.orders.map((o) => o.id).join(', ') || '(empty)'));
}

It prints

page 1: 4, 3, 2
page 2: 1
page 3: (empty)

It should print

page 1: 7, 6, 5
page 2: 4, 3, 2
page 3: 1

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 (orderService.js, line 5)

orderService.js line 5 works out the offset as page * limit, but pages start at 1, so page 1 skips the first limit orders: the newest ones, since the list is newest first. Every page is shifted one page along, and the last page runs off the end. It should be (page - 1) * limit.

The fix

orderService.js

2 3// One page of a customer's orders, newest first. Pages start at 1.4export async function listOrders(customer, page, limit) {5  const offset = page * limit;5  const offset = (page - 1) * limit;6  const orders = await findOrders({ customer }, { offset, limit });7  const total = await countOrders({ customer });8  return { orders, page, hasMore: offset + orders.length < total };

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 { getOrders } from './ordersRoute.js';
const first = await getOrders({ user: 'asha', query: { page: 1, limit: 3 } });
assert.deepEqual(first.body.orders.map((o) => o.id), [7, 6, 5]);
const last = await getOrders({ user: 'asha', query: { page: 3, limit: 3 } });
assert.deepEqual(last.body.orders.map((o) => o.id), [1]);

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

The newest orders are missing from page 1 of order history. Why?

Assistant

Your query is sorting orders oldest first, so page 1 shows the oldest orders. In findOrders, sort by date, newest first:

.sort((a, b) => b.placedAt - a.placedAt)
Show what’s wrong with its answer

The sort is already newest first (b.id - a.id): run findOrders({ customer: 'asha' }) on its own and the first row is order 7. The orders don’t even have a placedAt field, so the “fix” would compare undefineds and scramble the list. The AI guessed a common cause without reading the code. The evidence points elsewhere: log the offset for page 1 and it’s 3, not 0.

3Add a feature

The interviewer

Product wants a filter: GET /orders?status=delivered shows only delivered orders. Only delivered and cancelled are allowed; anything else is a 400. Paging must still work on the filtered list.

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

Validate against an allow-list in the route, so a bad value never reaches the query. Then pass the filter down and build one where, used by both the page query and the count, or hasMore would be computed on the unfiltered total.

The change

ordersRoute.js

1import { listOrders } from './orderService.js';2 3// GET /orders?page=1&limit=3 for the signed-in customer.3const STATUSES = ['delivered', 'cancelled'];4 5// GET /orders?page=1&limit=3&status=delivered for the signed-in customer.4export async function getOrders(req) {5  const page = Number(req.query.page ?? 1);6  const limit = Number(req.query.limit ?? 3);9  const status = req.query.status;7  if (!Number.isInteger(page) || page < 1) return { status: 400, body: { error: 'page must be 1 or more' } };8  if (!Number.isInteger(limit) || limit < 1 || limit > 50) return { status: 400, body: { error: 'limit must be 1 to 50' } };9  const body = await listOrders(req.user, page, limit);12  if (status !== undefined && !STATUSES.includes(status)) return { status: 400, body: { error: 'unknown status' } };13  const body = await listOrders(req.user, page, limit, status);10  return { status: 200, body };11}

orderService.js

1import { countOrders, findOrders } from './db.js';2 3// One page of a customer's orders, newest first. Pages start at 1.4export async function listOrders(customer, page, limit) {3// One page of a customer's orders, newest first. Pages start at 1. status is optional.4export async function listOrders(customer, page, limit, status) {5  const where = status ? { customer, status } : { customer };5  const offset = (page - 1) * limit;6  const orders = await findOrders({ customer }, { offset, limit });7  const total = await countOrders({ customer });7  const orders = await findOrders(where, { offset, limit });8  const total = await countOrders(where);8  return { orders, page, hasMore: offset + orders.length < total };9}

The test

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

import { getOrders } from './ordersRoute.js';
const res = await getOrders({ user: 'asha', query: { status: 'cancelled', limit: 5 } });
assert.equal(res.status, 200);
assert.deepEqual(res.body.orders.map((o) => o.id), [6, 3]);
assert.equal(res.body.hasMore, false);
assert.equal((await getOrders({ user: 'asha', query: { status: 'lost' } })).status, 400);

4Make it faster

The interviewer

Every request makes two queries: one for the page, and one that counts all the customer’s orders. On big accounts the count is the slow part. Make each request a single query, without changing what the API returns.

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

You don’t need the total to know whether there’s another page: ask for one row more than the page size. If it comes back, hasMore is true; then drop it before returning. One query instead of two, and the expensive count is gone. (For very deep pages, keyset paging, “newer than the last id I saw”, avoids large offsets too.)

The change

orderService.js

1import { countOrders, findOrders } from './db.js';1import { findOrders } from './db.js';2 3// One page of a customer's orders, newest first. Pages start at 1. status is optional.4// It fetches one row more than the page needs: if that row comes back, there's another page.4export async function listOrders(customer, page, limit, status) {5  const where = status ? { customer, status } : { customer };6  const offset = (page - 1) * limit;7  const orders = await findOrders(where, { offset, limit });8  const total = await countOrders(where);9  return { orders, page, hasMore: offset + orders.length < total };8  const rows = await findOrders(where, { offset, limit: limit + 1 });9  return { orders: rows.slice(0, limit), page, hasMore: rows.length > limit };10}

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 { getOrders } from './ordersRoute.js';
import { stats } from './db.js';
const before = stats.queries;
const res = await getOrders({ user: 'asha', query: { page: 2, limit: 3 } });
assert.equal(stats.queries - before, 1);
assert.deepEqual(res.body.orders.map((o) => o.id), [4, 3, 2]);
assert.equal(res.body.hasMore, true);
assert.equal((await getOrders({ user: 'asha', query: { page: 3, limit: 3 } })).body.hasMore, false);

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.