Skip to content

Instantly share code, notes, and snippets.

@neilzheng
Created October 4, 2024 08:18
Show Gist options
  • Save neilzheng/9fb2fe43492cfd48cd88e31e02047710 to your computer and use it in GitHub Desktop.
Save neilzheng/9fb2fe43492cfd48cd88e31e02047710 to your computer and use it in GitHub Desktop.
export interface PaginationArgs {
cursorName?: string;
cursor?: number;
forward?: number;
backward?: number;
skipPage?: number;
}
export const loadNewPageArgs = (
totalPage: number,
rowsPerPage: number,
cursorName: string,
pageStart: number,
pageEnd: number,
currentPage: number,
newPage: number,
): PaginationArgs => {
const firstPage = newPage === 1;
const lastPage = newPage === totalPage;
const pageOffset = newPage - currentPage;
const skipPage = Math.abs(pageOffset) - 1;
let direction = 'forward';
if ((!firstPage && pageOffset < 0) || lastPage) {
direction = 'backward';
}
let requestArgs = {};
if (direction === 'forward') {
// forward
requestArgs = {
forward: rowsPerPage,
};
if (!firstPage) {
requestArgs = {
...requestArgs,
cursorName,
cursor: pageEnd,
};
}
} else {
// backward
requestArgs = {
backward: rowsPerPage,
};
if (!lastPage) {
requestArgs = {
...requestArgs,
cursorName,
cursor: pageStart,
};
}
}
if (skipPage && !firstPage && !lastPage)
requestArgs = { ...requestArgs, skipPage };
return requestArgs;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment