I looked at https://math.stackexchange.com/questions/519845/modulo-of-a-negative-number and Modulo operation with negative numbers but I still wonder how to use a negative modulo value to get items in a range.
Here is a simplified use case before my question bellow, I have a slideshow with 3 slides (slidesCount = 3
):
slide indexes: 0 1 2
Now I would like to access the right slide from these numbers:
-2 -1 0 1 2 3 4
should match slide:
1 2 0 1 2 0 1
So with index % slidesCount
I cover the cases:
0 1 2 3 4
but not negative values. -1 % 3
returns -1
so is slidesCount + index % slidesCount
the correct expression if index is negative?
First of, is there a simpler/smarter way to write:
index = index % slidesCount + (index < 0 ? slidesCount : 0)
Now my question is for a slideshow of 3 visible items per slide, where the last slide may have only one item (index 9 bellow) so from these numbers:
-3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12
I want to match slides:
9 0 3 6 9 0
I hope the following diagram makes sense! Please help me get the correct equation out of it with minimum if
s:
-3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12
|________| |______________________________________________|
|| || ||
|| Math.floor( i / visibleSlides )
Math.ceil(i / visibleSlides) || ||
|| || ||
\/ \/ \/
-1 0 1 2 3 4
|___| |_______________________| |___|
|| || ||
slidesCnt + i % visibleSlides i % visibleSlides || ??
|| || ||
\/ \/ \/
3 0 1 2 3 0
|| i * visibleSlides
\/
9 0 3 6 9 0