Skip to content Skip to sidebar Skip to footer

Iterating Through A Range In Both Directions

There is a very common and easy task of looped iteration through some range in both directions: The code above works perfectly, but I spent about an hour trying to get rid of doub

Solution 1:

To turn the two ifs into one unconditional statement, you can add the range.length to the currentIndex and then use modulo:

var currentIndex = 0;
var range = ['a','b','c','d','e','f'];

functiongetNextItem(direction) {
    currentIndex = (currentIndex + direction + range.length) % range.length;
    return range[currentIndex];
}

// get next "right" itemconsole.log(getNextItem(1));
console.log(getNextItem(1));

// get next "left" itemconsole.log(getNextItem(-1));
console.log(getNextItem(-1));
console.log(getNextItem(-1));

console.log(getNextItem(4));
console.log(getNextItem(1));
console.log(getNextItem(1));
console.log(getNextItem(1));

Post a Comment for "Iterating Through A Range In Both Directions"