vue.js pagination mis calculation - javascript

In my app, I have some pagination code which calculates the pagination based on data from a REST API. When I add the page of pages, it is calculating from page 0 not from 1, so it says 0 of 9 and when it gets to the end it says 8 of 9, when it should say 1 of 9 and 9 of 9 at the end. So far my code is:
HTML
<p>Page {{page}} of {{pageCount}}</p>
JS
data: function() {
return {
page: 0
};
},
computed: {
pageCount() {
let l = this.result.length,
s = this.size;
return Math.floor(l / s);
},
paginated() {
const start = this.page * this.size,
end = start + this.size;
return this.result.slice(start, end);
}
},
Any ideas? Maybe I am calculating the math.floor method wrong?

Your page variable is 0 indexed instead of 1 index. You can keep it this way so that your pagination continues to work as intended, but where you are outputting it to the user you can simply add 1 so it makes sense to a user.
<p>Page {{page + 1}} of {{pageCount}}</p>

From what I understood, your pageCount() method is correct because you indeed have 9 pages so math.floor is not the problem, your page variable is the one that is incorrect but I cannot see where you are getting that variable from but a simple yet coarse solution would be just to add 1 to the variable.

Related

pagination with dots in React using Javascript

I am building pagination where I want to display '...' at certain points. The amount of pages is dictated by user selection; there are 650-ish posts, and users can choose to display 15, 25, 50, or 100 items at a time. Anyway, let's say that there are 45 pages.
If I am on page one, I want it to look like this:
1 2 3 ... 45
if I am on page 3, I want it to look like this:
1 ... 2 3 4 ... 45
if I am on page 44 (or 45), I want it to look like this:
1... 43 44 45
I am doing this all with JS, I'm not using any extra pagination packages from React. Currently, I have some functionality but I am getting stumped on how to adjust my for loop.
So, right now, if I am on page 1, it looks like :
1 2 ... 43 44 45
If I'm on page 3 :
1 2 3 4 ... 43 44 45
If I am on page 4:
1... 3 4 5 ... 43 44 45
**If I am on page 45:
1 ... 44 45
I looked around for a long time, and finally found a stackoverflow thread that helped. I implemented the basic while loop provided by derpirscher.
let pagination = [], i = 1;
while (i <= totalPageCount) {
if (i <= 1 ||
i >= totalPageCount - 2||
i >= currentPage - 1 && i <= currentPage + 1) {
pagination.push(i);
i++;
} else {
pagination.push('...');
//jump to the next page to be linked in the navigation
i = i < currentPage ? currentPage - 1 : totalPageCount - 2;
}
}
In this example, totalPageCount is how many pages there are total, and currentPage is the page the user is currently on. I tried to incorporate some sibling logic where if, for example, the left sibling index was greater than two, I inserted dots. That just resulted in there being dots on the left side of just about every page number, and I definitely didn't want that.
If it is important, I map through pagination directly in my render function to generate the template.
{pagination.map((pageNumber) => {
return (
<li key={pageNumber}>
<button
onClick={() => onPageChange(pageNumber)}
>
{pageNumber}
</button>
</li>
)
})}
Any thoughts or useful resources on this would be appreciated. I know my JS could be better, which is partly why I am trying to practice doing it this way!

pagination in javascript showing amount of elements per page

${totalItems} = 22
${pageSize} = 10
I would like to know how can I create a calculation.
like that: first will show 1 - 10 items, if i click in the next page will show: 11 - 20 and the last one will be 21 - 22.
so basically the calculation will be showing the numbers 1 -10 then 11-20 everytime i click in the next page in my pagination.
can someone give a javascript sample for this? the only value I have is 22, so I would like do a calculation like I said above. and display this in my html.
Getting the index of the first item on a page
To get the first index of a page, you multiple the current page number by the number of items per page:
firstIndex = pageSize * pageNr
For your example:
console.log(
"Start of each page:",
[0, 1, 2].map(pageNr => 10 * pageNr)
);
Getting the index of the last item on a page
To get the index of the last item in a page, we can use this function to get the starting index of the next page, and subtract 1:
lastIndex = pageSize * (pageNr + 1) - 1
console.log(
"End of each page:",
[0, 1, 2].map(pageNr => 10 * (pageNr + 1) - 1)
);
Finding out how many pages there are
To see how many pages we need to render all our items, we divide the total number of items by the page size and round upwards using Math.ceil:
nrOfPages = Math.ceil(nrOfItems / pageSize)
Writing the actual code
Now that we've got the basic "math" covered, we can start writing actual functions and create a small app.
Depending on the format of the data, you can build some safety checks to make sure you cannot:
Request a page number that is out of range,
Request a negative page number
Input a 0 or negative page size,
etc.
Since you haven't provided anything useful to work with, I'm going to skip these measures and show you an example based on one array of items to paginate:
function getPageStart(pageSize, pageNr) {
return pageSize * pageNr;
};
function getPageLabel(total, pageSize, pageNr) {
const start = Math.max(
getPageStart(pageSize, pageNr),
0
);
const end = Math.min(
getPageStart(pageSize, pageNr + 1),
total
);
return `${start + 1} - ${end}`;
}
const itemsToShow = Array.from({ length: 22 }, (_, i) => `Item ${i + 1}`);
const size = 10;
const pages = Array.from(
{ length: Math.ceil(itemsToShow.length / size) },
(_, i) => getPageLabel(itemsToShow.length, size, i)
)
console.log(pages);

Find an intermediate value for MOD factor

I am developing an app. At 5 pm, the array resets and count starts from 0 and by the end of day there are thousands of values inside the array. There is a very simple code inside my logic. My data is inside the array data.
data.forEach(function(entry) {
if (entry.time_stamp >= tsYesterday) {
if (count % 100 == 0) {
element = { x: new Date(entry.time_stamp), y: entry.occupied_count };
history_slots.push(element);
}
count++;
}
But the issue is that at 5 pm when there is just 1 element inside the array, it doesn't gets displayed because (0-99)%100 so I want to replace 100 with something. Can I change the value of MOD Factor on the basis is array length? Please guide me if you understand my question.
Thanks in advance.

Random link javascript to ignore current page

When I click the 'Random' link on my navbar (bootstrap) it refers to Javascript code (below) taking me to a random page on my mock website.
However I would like to add a feature, so if I'm on, say Link[2]=fed-rates.html, when I press the 'Random' link on my navbar it always takes me away from the page I'm currently on (that is, it ignores Link[2]).
I'm wondering whether this is possible, would be great to get some ideas.
Javascript code:
function randomlinks(){
var myrandom=Math.round(Math.random()*2)
var links=new Array()
links[0]="articles/how-to-trade-oil.html"
links[1]="articles/usd-yen-gbp.html"
links[2]="articles/fed-rates.html"
window.location=links[myrandom]
}
// above is for all web pages
function randomlinksarticle(){
var myrandom=Math.round(Math.random()*2)
var links=new Array()
links[0]="how-to-trade-oil.html"
links[1]="usd-yen-gbp.html"
links[2]="fed-rates.html"
window.location=links[myrandom]
}
// above is so navbar link still works on the linked pages, with the way I have the folder directory setup
New code that comes up with "/undefined" page:
function randomlinksarticle(){
var myrandom=Math.round(Math.random()*2)
var links=new Array()
links[0]="how-to-trade-oil.html"
links[1]="usd-yen-gbp.html"
links[2]="fed-rates.html"
links.forEach(function(link, index) {
if (location.href.indexOf(link) !== -1) {
links.splice(index, 1);
}});
window.location=links[myrandom]
You can do the following:
links.forEach(function(link, index) {
if (location.href.indexOf(link) !== -1) {
links.splice(index, 1);
}
});
This looks through all the links and checks if they exist in the current URL. If they do, it removes them from the list using the splice function.
Add this code after setting link[2], since that's when it should be removing the current page.
Edit: I also noticed that your random function isn't evenly distributed. Not that it matters that much, but it could cause problems for you. The reason for this is that there are many more numbers between 0 and 2 that round to 1 than to 0 or two. In order to get a zero from your random number scale, Math.random() has to be less than 0.5. Likewise, it has to be greater than or equal to 1.5 to get a 2. you have a 0.5/2 or 1/4 probability for 0 and 2. This leaves a 1/2 probability for getting one, which makes sense since all numbers between 0.5 and 1.5 would give you a 1.
tl;dr: Use math.floor(Math.random() * (maximum + 1)) rather than Math.round(Math.random() * maximum) for generating random numbers.
Also, if you want a less repetitive way to do this, you could substitute both functions for something like this:
function randomLink() {
var links = Array.prototype.slice.call(arguments, 0); //Turns the function's arguments into an array
links.forEach(function(link, index) { //Loops through all the links
if (location.href.indexOf(link) !== -1) { //If the link text is contained in the url
links.splice(index, 1); //Remove the link from the links array
}
});
var rand = Math.floor(Math.random() * links.length); //Choose a number between 0 and links.length - 1
window.location = links[rand]; //Visit the link
}
You could call this like randomLink("first_page.html", "second_page.html") with an arbitrary number of pages.

Javascript if statement not working ecommerce

The site I'm working on requires that if the total amount is less than 399 then a delivery fee of 100 is to be charged. However I put:
//<![CDATA[
simpleCart({
if(total<399){shippingFlatRate: 100;}
});
//]]>
the main function has the total amount and that works and flat rate is set on, but when I use this if statement it stays on 0 and doesn't become 100.
If you are trying to set the property of an object then your syntax is wrong. Try this:
shippingFlatRate: total < 399 ? 100 : 0
Seems to be the wrong coded. If you have an object and needs to define a variable with a conditional, you can make this:
simpleCart({
shippingFlatRate: function() {
if(total<399){
return 100; //it takes 100 of value
} else {
return 0; // it takes 0 of value
}
}
});

Categories