Skip to content

Instantly share code, notes, and snippets.

@yinkakun
Last active June 8, 2023 12:53
Show Gist options
  • Save yinkakun/98ab0120507904e80e93ac93adc8c852 to your computer and use it in GitHub Desktop.
Save yinkakun/98ab0120507904e80e93ac93adc8c852 to your computer and use it in GitHub Desktop.
const getPagination = (currentPage: number, totalPages: number) => {
const BOUNDARY = 5;
const MIN_PAGE = 1;
const MAX_PAGE = Math.max(MIN_PAGE, totalPages);
const prevPage = currentPage > MIN_PAGE ? currentPage - 1 : null;
const nextPage = currentPage < MAX_PAGE ? currentPage + 1 : null;
let prevPages: number[] = [];
let nextPages: number[] = [];
for (let i = Math.max(MIN_PAGE + 1, currentPage - BOUNDARY); i < currentPage; i++) {
prevPages.push(i);
}
for (let i = currentPage + 1; i <= Math.min(MAX_PAGE - 1, currentPage + BOUNDARY); i++) {
nextPages.push(i);
}
return {
prevPage,
nextPage,
nextPages,
prevPages,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment