Skip to content

Instantly share code, notes, and snippets.

@brianzelip
Created February 4, 2021 11:52
Show Gist options
  • Save brianzelip/b73931458e4ba15158dd802aa7bdb0aa to your computer and use it in GitHub Desktop.
Save brianzelip/b73931458e4ba15158dd802aa7bdb0aa to your computer and use it in GitHub Desktop.
Use the modulo operator for a looping slide show
// When making a looping slide show, here's the long way to get at what the modulo operator provides
if (counter < images.length - 1) {
counter++;
} else {
counter = 0;
}
const prevIndex = counter < 1 ? images.length - 1 : counter - 1;
const currIndex = counter;
const nextIndex = counter == images.length - 1 ? 0 : counter + 1;
// Modulo
const prevIndex = (counter - 1 + images.length) % images.length)
const nextIndex = (counter + 1) % images.length;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment