@padhariyavishal/offset-pagination
Version:
Offset pagination package to help dynamically create an pagination of items array
33 lines (32 loc) • 1.22 kB
JavaScript
;
// index.ts
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataPagination = void 0;
function DataPagination(items, currentPage, itemsPerPage, midSize) {
if (currentPage < 1 || itemsPerPage < 1 || midSize < 0) {
throw new Error("Invalid arguments. Current page, items per page, and mid-size must be positive numbers.");
}
const totalItems = items.length;
const totalPages = Math.ceil(totalItems / itemsPerPage);
if (currentPage > totalPages) {
throw new Error("Current page exceeds total pages.");
}
const startPage = Math.max(1, currentPage - midSize);
const endPage = Math.min(totalPages, currentPage + midSize);
const pages = [];
for (let i = startPage; i <= endPage; i++) {
pages.push(i);
}
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = Math.min(startIndex + itemsPerPage, totalItems);
const currentItems = items.slice(startIndex, endIndex);
return {
currentPage,
totalPages,
pages,
hasPreviousPage: currentPage > 1,
hasNextPage: currentPage < totalPages,
items: currentItems,
};
}
exports.DataPagination = DataPagination;