Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pagination calculation algorithm

I am trying to calculate pagination:

var pagination = {
 total: result.length,
 per_page: itemsPerPage,    // required
 current_page: currentPage, // required
 last_page: users.length / itemsPerPage,    // required
 from: (itemsPerPage * pageNumber) + 1,
 to: itemsPerPage * (pageNumber + 1)           //required
};

Let say the result length is 2, itemsPerPage is 5, currentPage is 1, I got this:

total: 2
per_page: 5
current_page: 1
last_page: 0.4
from: 6
to: 10

I think something is not right.

like image 375
Alvin Avatar asked Sep 23 '16 23:09

Alvin


People also ask

How is page pagination calculated?

total_items / 10 should give you the number of pages. You also need to consider remainder of the division (total_items % 10). So total pages would be total_items / 10 and 1 more in case remainder is > 0.

How is offset value of pagination calculated?

$offset = ($page - 1) * $items_per_page; Then replace the $page accordingly.

What is the logic of pagination?

The paginate function accepts the following parameters: totalItems (required) - the total number of items to be paged. currentPage (optional) - the current active page, defaults to the first page. pageSize (optional) - the number of items per page, defaults to 10.

What is dynamic pagination?

Create dynamic pagination links. Allows you to truncate as well as call a function on page change.


1 Answers

To round for the max value, you can use Math.ceil on last_page.

The items per page can be static, manually defined. Then, from can be ((currentPage - 1) * itemsPerPage) + 1.

  • If current page is 1, ( (1 -1) * 5) + 1 = 1.
  • Second page: ( (2 -1) * 5) + 1 = 6, and so on.

Then it can be currentPage * itemsPerPage. Eg if the current page is 1, then 1 * 5 = 5, if its the second page it will be: 2 * 5 = 10. Look below for an example:

var pagination = {
 total: result.length,
 per_page: itemsPerPage,    
 current_page: currentPage, 
 last_page: Math.ceil(result.length / itemsPerPage),
 from: ((currentPage -1) * itemsPerPage) + 1,
 to: currentPage  * itemsPerPage
};
Total = 15;
per_page = 5;
currentPage = 1;
last_page = truncate (15 / 5) = 3;
from: ((1-1) * 5) + 1 = 1 //first page
      ((2-1) * 5) + 1 = 6 //second page
to: 1 * 5 = 5 //first page
    2 * 5 = 10 // second page
From 1 to 5 // first page
From 6 to 10 // second page
From 11 to 15 // last page
like image 57
BrTkCa Avatar answered Sep 24 '22 04:09

BrTkCa