create a function that will iterate an array left or right and return the index each time in javascript

Here's a function that will iterate an array left or right and return the index each time:

index.tsx
function iterateArray(arr, direction) {
  var currentIndex = 0;
  if (direction === 'left') { // iterate left
    return function() {
      currentIndex--;
      if (currentIndex < 0) {
        currentIndex = arr.length - 1;
      }
      return currentIndex;
    };
  } else if (direction === 'right') { // iterate right
    return function() {
      currentIndex++;
      if (currentIndex >= arr.length) {
        currentIndex = 0;
      }
      return currentIndex;
    };
  } else {
    return 'Invalid direction';
  }
}
525 chars
23 lines

To use it, first create the function with the array and direction as arguments:

index.tsx
var arr = [1, 2, 3, 4, 5];
var direction = 'right';
var iterator = iterateArray(arr, direction);
97 chars
4 lines

Then, call the iterator function to get the next index each time:

index.tsx
console.log(iterator()); // 0
console.log(iterator()); // 1
console.log(iterator()); // 2
console.log(iterator()); // 3
console.log(iterator()); // 4
console.log(iterator()); // 0 (wraps around to beginning)
208 chars
7 lines

gistlibby LogSnag