Alvin Alvin - 2 months ago 37
Node.js Question

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.

Answer

To round for the max value, you can use Math.ceil, at last_page. The itens per page can be static, manually defined. Now, 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. The to can be currentPage * itemsPerPage. If current page is 1, then 1 * 5 = 5. Second page: 2 * 5 = 10. Look this:

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

Comments