One simple yet commonly encountered task involves looping through a range forwards and backwards:
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 snippet above functions efficiently, although I spent close to an hour attempting to eliminate the duplicate if
check.
Is there a way to solve this issue without using an if
statement? Perhaps in a more concise one-liner approach?