Skip to content
← All exercises

Pagination that loses the last item

TypeScript · A list endpoint in a REST API · Logic · difficulty 1/3 · ~5 min

A colleague asked the AI assistant: "Write a function paginate(items, page, pageSize) for our list endpoint. Pages start at 1. Return the items of the requested page plus pagination info."

The code came back in thirty seconds, with passing tests. The contract promised by the docstring:

  • page starts at 1; pageSize is the maximum number of items per page.
  • items contains the items of the requested page, in their original order.
  • totalPages is the number of pages needed for all items.
  • hasNext is true when there is a page after the requested one.

Review it before it goes in.

Repair the code until the hidden tests pass.

code.ts

Visible tests (they pass on the code as given)
import { describe, it, expect } from "@debunk/harness";
import { paginate } from "./code";

describe("paginate", () => {
  it("returns the first page", () => {
    const r = paginate([1, 2, 3, 4, 5, 6], 1, 2);
    expect(r.items).toEqual([1, 2]);
    expect(r.page).toBe(1);
  });

  it("computes totalPages for evenly divisible lists", () => {
    expect(paginate([1, 2, 3, 4, 5, 6], 1, 3).totalPages).toBe(2);
  });

  it("hasNext is false on the last page of an evenly divisible list", () => {
    expect(paginate([1, 2, 3, 4], 2, 2).hasNext).toBe(false);
  });
});