Reputation: 63
const idx = query.idx;
let page = 1;
if (idx > 19){
page = 2
};
if (idx > 39){
page = 3
};
if (idx > 59){
page = 4
};
console.log(page);
This is my code I am trying to change the page variable after every 19, 39, 59 etc is there a better way to write this code as if i have more indexes i will need to add more ifs
Upvotes: 2
Views: 97
Reputation: 657
This should be a solution
const idx = query.idx;
let page = Math.floor(idx / 20) + 1;
console.log(page);
if you need to use only ifs:
if (idx > 19 && idx < 40){
page = 2
};
if (idx > 39 && idx < 60){
page = 3
};
if (idx > 59){
page = 4
};
Upvotes: 0
Reputation: 193261
Divide by 20 (page size) and round result. Something like this:
const idx = query.idx;
const page = Math.ceil((idx + 1) / 20)
console.log(page);
Couple of tests:
[
1,
5,
15,
19,
20,
21,
36,
39,
40,
41,
49,
59,
60,
68,
].forEach(idx => {
console.log(idx, Math.ceil((idx + 1) / 20))
})
Upvotes: 5
Reputation: 73908
Try the following
const findPage = (idx, limit)=> Math.ceil(idx / limit)+1
console.log(findPage(19, 20))
console.log(findPage(39, 20))
console.log(findPage(59, 20))
Upvotes: 0