Skip to content

List pagination info

Web / frontend · Difficulty 2/5 · JavaScript · 30 linesOrigin: Fictional

Task

What the AI was asked to do

Write getPageInfo(requestedPage, totalItems, pageSize) for the product list's pagination bar. requestedPage is an integer from the URL; if it is out of range, move it to the nearest valid page. pageSize is a positive integer. Return the current page, the total number of pages, a label like 11–20 / 45, whether there is a previous and a next page, and at most 5 page numbers (with the current page in the middle where possible). With no products there is one empty page, labeled 0–0 / 0.

Handoff note

What the AI wrote when it handed over the code:

“The page number is always moved into the valid range, and the empty list is handled. The label and the page numbers are right in every case.”

The code the AI wrote

JavaScript30 lines

Mark the lines you think are wrong; give each mark a severity and a one-sentence reason.

Click or tap a line. With a keyboard, move to the line and press Enter.

0 of 5 marks
How to pick a severity
  • CriticalData loss, a security hole or lost money
  • MajorThe user gets a wrong result in a case the task asks for
  • MinorA rare edge case outside the task, or readability

In the Testing topic, severity is set by the effect of the broken implementation the test doesn't catch.

Your reason isn't graded; you'll compare it with a sample answer.

const VISIBLE_PAGES = 5;
2
function visiblePages(page, totalPages) {
  const half = Math.floor(VISIBLE_PAGES / 2);
  const start = Math.max(
    1,
    Math.min(page - half, totalPages - VISIBLE_PAGES + 1),
  );
  const end = Math.min(totalPages, start + VISIBLE_PAGES - 1);
  const pages = [];
  for (let number = start; number <= end; number += 1) {
    pages.push(number);
  }
  return pages;
}
16
export function getPageInfo(requestedPage, totalItems, pageSize) {
  const totalPages = Math.max(1, Math.floor(totalItems / pageSize));
  const page = Math.min(Math.max(requestedPage, 1), totalPages);
  const firstItem = totalItems === 0 ? 0 : (page - 1) * pageSize + 1;
  const lastItem = Math.min(page * pageSize, totalItems);
  return {
    page,
    totalPages,
    label: `${firstItem}–${lastItem} / ${totalItems}`,
    hasPrevious: page > 1,
    hasNext: page < totalPages,
    pages: visiblePages(page, totalPages),
  };
}

The test that proves it

The right option is the test that fails on this code, which means it exposes the bug.

Test options
Mark at least one line to submit.

Submitting sends seven pieces of information to a counter; your reason text stays on your device. Data