I am building a pagination system for a table and want to show a text like 1 to 5 of 14 entries
i have the following code
var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 1;
var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);
var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);
var end = start + numberOfItemsPerPage - 1;
console.log(`${start} to ${end} of ${totalItemsCount}`);
now this works well when the number of items per page can equally divide the total number of items but when that is not the case end
will be incorrect. in the following case if the variable page
is 3 end
will be of by 1
. how can i fix this?
I suggest to use a slightly different approach for calculating the parameter.
var pagination = (page, total, itemsOnPage) => {
var numberOfPages = Math.ceil(total / itemsOnPage),
start = (page - 1) * itemsOnPage + 1,
end = Math.min(page * itemsOnPage, total);
return `${start} to ${end} of ${total} on page ${page} of ${numberOfPages}`;
};
console.log(pagination(1, 14, 5));
console.log(pagination(2, 14, 5));
console.log(pagination(3, 14, 5));
console.log(pagination(3, 15, 5));
You could use Math.min
.
var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);
e.g.
var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 3;
var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);
var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);
var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);
console.log(`${start} to ${end} of ${totalItemsCount}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With