Using modulus to cycle an array

by sidonaldson

JavaScript

var theArray = [0, 1, 2, 3, 4, 5];
var currentIndex = 0;

function getAtIndex(i) {
  if (i === 0) {
    return theArray[currentIndex];
  } else if (i < 0) {
    return theArray[(currentIndex + theArray.length + i) % theArray.length];
  } else if (i > 0) {
    return theArray[(currentIndex + i) % theArray.length];
  }
}

document.body.innerHTML = getAtIndex(-2) + " - " + getAtIndex(1) + " - " + getAtIndex(8);