function to return previous current and next indexes on array with increment and decrement functions in javascript

index.tsx
function getIndexes(arr, currentIndex) {
  const previousIndex = currentIndex === 0 ? arr.length - 1 : currentIndex - 1;
  const nextIndex = currentIndex === arr.length - 1 ? 0 : currentIndex + 1;

  return {
    previous: previousIndex,
    current: currentIndex,
    next: nextIndex,
  };
}

function incrementIndex(arr, currentIndex) {
  return getIndexes(arr, (currentIndex + 1) % arr.length);
}

function decrementIndex(arr, currentIndex) {
  return getIndexes(arr, (currentIndex - 1 + arr.length) % arr.length);
}
520 chars
19 lines

This code defines a function getIndexes that takes an array and a current index, and returns an object with the previous, current and next indexes based on the currentIndex.

The incrementIndex and decrementIndex functions take an array and a currentIndex, and call getIndexes to retrieve the next or previous index respectively.

Note that the incrementIndex function uses a modulo operation to cycle back to the first element of the array once the last element is reached, while the decrementIndex function uses modular arithmetic to cycle back to the last element of the array once the first element is reached.

gistlibby LogSnag