Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ponnex/2a9e1c5adf3f9ed289bd675020b3b41d to your computer and use it in GitHub Desktop.
Save ponnex/2a9e1c5adf3f9ed289bd675020b3b41d to your computer and use it in GitHub Desktop.
Truncated Pagination with Variable Fixed Length
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