All files / src/app/teacher-page/page/class-list paginateClassList.js

100% Statements 9/9
100% Branches 10/10
100% Functions 1/1
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                                                    15x 3x   12x 3x   9x 9x 15x 15x 15x            
/**
 * EI-2727 — Teacher Classes pagination helper.
 *
 * Pure function that slices an already-filtered class list to a single
 * page.  Extracted so the page-math is unit-testable independently of
 * Main.jsx / MUI Pagination component.
 *
 * The backend caps a teacher at 10 classes today (see
 * `server/utilities/class_limits.py`), so client-side pagination is
 * a UX nicety for now — but the slice already mirrors backend
 * pagination metadata in `_pagination` (totalCount, pageSize,
 * currentPage, overAllEntries) so this can later move server-side
 * without an API rewrite.
 *
 * Contract:
 *   - `page` is 1-based (matches MUI Pagination component).
 *   - Out-of-range pages clamp to the closest valid page rather than
 *     returning an empty slice — prevents the UI from showing "no
 *     classes" when the teacher hits Next past the last page (a
 *     subtle UX trap MUI Pagination's `page` prop can produce when
 *     stale state survives a re-filter).
 *   - When `classList` is empty or page-size is non-positive, return
 *     `{ rows: [], totalPages: 0, clampedPage: 1 }`.
 */
 
export function paginateClassList(classList, page, pageSize) {
    if (!Array.isArray(classList) || classList.length === 0) {
        return { rows: [], totalPages: 0, clampedPage: 1 };
    }
    if (!Number.isFinite(pageSize) || pageSize <= 0) {
        return { rows: [], totalPages: 0, clampedPage: 1 };
    }
    const totalPages = Math.ceil(classList.length / pageSize);
    const clampedPage = Math.min(Math.max(1, Math.trunc(page) || 1), totalPages);
    const start = (clampedPage - 1) * pageSize;
    const end = start + pageSize;
    return {
        rows: classList.slice(start, end),
        totalPages,
        clampedPage,
    };
}