bi-directional array index looping function that return index for each left or right traversal in javascript

Here is a function that does bi-directional array index looping and returns the index for each left or right traversal in JavaScript:

index.tsx
function biDirectionalArrayIndexLooping(arr, start, direction, steps) {
    const n = arr.length;
    let index = start;
    for (let i = 0; i < steps; i++) {
        index = ((index + direction) % n + n) % n;
        console.log(index);
    }
    return index;
}
264 chars
10 lines

The function takes in an array arr, a starting index start, a direction direction (-1 for left, 1 for right), and the number of steps to take steps.

In each iteration of the loop, we calculate the next index in the given direction using the formula (index + direction) % n. This gives us the index of the next element we should be looking at.

However, we need to handle the case where the resulting index goes out of bounds (i.e. less than 0 or greater than or equal to the length of the array). To do this, we add the length of the array to the result and then take the modulus again. This gives us the correct index for looping around the array.

We then print out the new index and continue looping until we have taken the specified number of steps.

Finally, we return the index of the last element we visited.

gistlibby LogSnag