JW Paginate

1.0.4 · maintenance · verified Sun Apr 19

jw-paginate provides a standalone, framework-agnostic utility for calculating pagination logic, implemented in both JavaScript and TypeScript. It offers a pure function that, given parameters like total items, current page, page size, and maximum pages to display, returns a comprehensive object containing all necessary pagination details. This includes total pages, start and end item indices, start and end page numbers, and an array of page numbers to render in a UI. The current stable version is 1.0.4. Due to its minimalist 'pure logic' design and comprehensive feature set for its specific domain, the library has a very infrequent release cadence, with its last significant update occurring in 2018. Its primary differentiator is its complete lack of external dependencies and framework agnosticism, allowing seamless integration into any web project without introducing framework-specific couplings or unnecessary bloat. It also ships with first-class TypeScript type definitions, providing an enhanced development experience for TypeScript users.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `paginate` function to calculate page numbers and slice a data array for a specific page. It initializes an array of items and then uses the `jw-paginate` function to determine the pagination details for a given page, logging the results.

import paginate from 'jw-paginate';

interface Item {
  id: number;
  name: string;
}

const allItems: Item[] = Array.from({ length: 150 }, (_, i) => ({
  id: i + 1,
  name: `Item ${i + 1}`
}));

// Simulate a request for page 3 with 10 items per page
const currentPage = 3;
const pageSize = 10;
const maxPagesToShow = 7;

const page = paginate(
  allItems.length, 
  currentPage, 
  pageSize, 
  maxPagesToShow
);

const pageOfItems = allItems.slice(page.startIndex, page.endIndex + 1);

console.log(`Total Items: ${page.totalItems}`);
console.log(`Total Pages: ${page.totalPages}`);
console.log(`Current Page: ${page.currentPage}`);
console.log(`Page Numbers to Display: ${page.pages}`);
console.log(`Showing items ${page.startIndex + 1} to ${page.endIndex + 1}:`);
pageOfItems.forEach(item => console.log(` - ${item.name}`));

// Example: Pagination for a different scenario
const anotherPage = paginate(50, 1, 5, 5);
console.log('\n--- Another Pagination Example ---');
console.log(`Total Pages: ${anotherPage.totalPages}`);
console.log(`Page Numbers: ${anotherPage.pages}`);

view raw JSON →