Advertisements
I guess everybody has had this scenario when implementing a pagination: You are on the first or last element and the user goes forth or back and starts a new rotation. My naive implementation is this:
let total = 3;
let index = 0;
const goto = (where) => {
index += where === 'prev' ? -1 : 1;
if (index < 0) index = total - 1;
if (index >= total) index = 0;
document.getElementById('b').textContent = index;
}
document.getElementById('a').addEventListener('click', () => goto('prev'));
document.getElementById('c').addEventListener('click', () => goto('next'));
<button id="a" type="button">Prev</button>
<span id="b">0</span>
<button id="c" type="button">Next</button>
Is there a way to simplify these cumbersome if-clauses using some clever math? Also, is a possible alternative also easy to read and to follow for somebody else reading the code?
>Solution :
You could take the offsets of prev
and next
as variable and use the remainder to get a value between zero (with) and total (without).
const
prev = -1,
next = 1,
total = 3;
let index = 0;
const goto = (where) => {
index += total + where; // prevent negative value
index %= total; // get interval
document.getElementById('b').textContent = index;
};
document.getElementById('a').addEventListener('click', () => goto(prev));
document.getElementById('c').addEventListener('click', () => goto(next));
<button id="a" type="button">Prev</button>
<span id="b">0</span>
<button id="c" type="button">Next</button>