There is a very common and easy task of looped iteration through some range in both directions:
var currentIndex = 0;
var range = ['a', 'b', 'c', 'd', 'e', 'f'];
function getNextItem(direction) {
currentIndex += direction;
if (currentIndex >= range.length) { currentIndex = 0; }
if (currentIndex < 0) { currentIndex = range.length-1; }
return range[currentIndex];
}
// get next "right" item
console.log(getNextItem(1));
// get next "left" item
console.log(getNextItem(-1));
The code above works perfectly, but I spent about an hour trying to get rid of double if
check.
Is there any way to solve if without if? Sort of one-liner maybe?