Created
October 21, 2025 15:27
-
-
Save graffhyrum/7f803e3d7df3a1b262ddb55a446e2769 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import {test, expect} from "bun:test"; | |
| import {getPagination, type PaginationArgs} from "./paginate.ts"; | |
| const baseArgs: PaginationArgs = { | |
| currentPage: 7, | |
| numberOfDisplayPages: 10, | |
| resultsPerPage: 10, | |
| totalResults: 175 | |
| } | |
| test('left edge', () => { | |
| const results = getPagination({ | |
| ...baseArgs, | |
| currentPage: 2 | |
| }) | |
| expect(results).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) | |
| }) | |
| test('center', () => { | |
| const results = getPagination(baseArgs) | |
| expect(results).toEqual([2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) | |
| }) | |
| test('right edge', () => { | |
| const results = getPagination({ | |
| ...baseArgs, | |
| currentPage: 17 | |
| }) | |
| expect(results).toEqual([9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) | |
| }) | |
| test('undersized window', () => { | |
| const args: PaginationArgs = { | |
| currentPage: 2, | |
| numberOfDisplayPages: 1000, | |
| resultsPerPage: 10, | |
| totalResults: 15 | |
| } | |
| const results = getPagination(args) | |
| expect(results).toEqual([1, 2]) | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export type PaginationArgs = { | |
| currentPage: number | |
| totalResults: number | |
| resultsPerPage: number | |
| numberOfDisplayPages: number | |
| } | |
| export function getPagination(args: PaginationArgs): number[] { | |
| const {currentPage, totalResults, resultsPerPage, numberOfDisplayPages} = args | |
| const totalPages = Math.ceil(totalResults / resultsPerPage) | |
| let startPage = Math.max(1, currentPage - Math.floor(numberOfDisplayPages / 2)) | |
| let endPage = Math.min(totalPages, startPage + numberOfDisplayPages - 1) | |
| // Adjust startPage to show full window when near end | |
| startPage = Math.max(1, endPage - numberOfDisplayPages + 1) | |
| const result = [] | |
| for (let i = startPage; i <= endPage; i++) { | |
| result.push(i) | |
| } | |
| return result | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment