DEV Community

Discussion on: This simple math hack lets you create an image carousel without any if statements

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
const imageData = [ 'image1.png', 'img2.png', 'img3.png' ];
let currentImage = 0;

const handleImageChange = (direction) => {
    currentImage = (currentImage + imageData.length + ((direction == 'forward') ? 1 : -1)) % imageData.length;
}
Collapse
 
ranewallin profile image
Rane Wallin

I don't think this will work as written. You only add the number of elements to the first part if you are going backwards. This looks like it's adding it either way. If I am at the last element (2) in this example then this would return in the next index being 3 instead of 0.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Wrong. Adding either way works. 3 modulo 3 is zero, as is 6 modulo 3, 9 modulo 3 etc.

Collapse
 
mrwensveen profile image
Matthijs Wensveen

If you create a direction enum like so:

const direction = { FORWARD: 1, BACKWARD: -1 },

const handleImageChange = offset => {
  currentImage = (currentImage + imageData.length + offset) % imageData.length;
}

// call with enum value:
handleImageChange(direction.BACKWARD);

And you're golden. Well, except when you call handleImageChange(-7)

Solution: currentImage = (currentImage + imageData.length + (offset % imageData.length)) % imageData.length
😊