Created
June 29, 2022 06:39
-
-
Save ponnex/2a9e1c5adf3f9ed289bd675020b3b41d to your computer and use it in GitHub Desktop.
Truncated Pagination with Variable Fixed Length
This file contains 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
const MINIMUM_PAGE_SIZE = 5; | |
const getRange = (start: number, end: number) => { | |
const length = end - start + 1; | |
return Array.from({length}, (_, i) => start + i); | |
}; | |
const clamp = (number: number, lower: number, upper: number) => { | |
return Math.min(Math.max(number, lower), upper); | |
} | |
const pagination = (currentPage: number, pageCount: number, pageSize: number) => { | |
let delta: number; | |
currentPage = clamp(currentPage, 1, pageCount); | |
pageSize = clamp(pageSize, MINIMUM_PAGE_SIZE, pageCount); | |
const centerPageSize = pageSize - 5; | |
const boundaryPageSize = pageSize - 3; | |
if (pageCount <= pageSize) { | |
delta = pageSize; | |
} else { | |
delta = | |
currentPage < boundaryPageSize || currentPage > pageCount - boundaryPageSize | |
? boundaryPageSize | |
: centerPageSize; | |
} | |
const range = { | |
start: Math.round(currentPage - delta / 2), | |
end: Math.round(currentPage + delta / 2), | |
}; | |
if (range.start - 1 === 1 || range.end + 1 === pageCount) { | |
range.start += 1; | |
range.end += 1; | |
} | |
let pages: (string | number)[] = | |
currentPage > delta | |
? getRange( | |
Math.min(range.start, pageCount - delta), | |
Math.min(range.end, pageCount), | |
) | |
: getRange(1, Math.min(pageCount, delta + 1)); | |
if (currentPage > pageCount - boundaryPageSize) { | |
pages = getRange(pageCount - delta, pageCount); | |
} | |
const withDots = (value: number, pair: (string | number)[]) => | |
pages.length + 1 !== pageCount ? pair : [value]; | |
if (pages[0] !== 1) { | |
pages = withDots(1, [ | |
1, | |
'...', | |
]).concat(pages); | |
} | |
const lastPage = pages[pages.length - 1]; | |
if (lastPage && lastPage < pageCount) { | |
pages = pages.concat( | |
withDots(pageCount, [ | |
'...', | |
pageCount, | |
]), | |
); | |
} | |
return pages; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment