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

Here's an implementation of a bi-directional array index looping function using JavaScript. It takes an input array and the starting index and returns the index plus index on each side for each left or right traversal.

index.tsx
function biDirectionalArrayIndexLooping(arr, start) {
  const length = arr.length;
  const result = [];

  // loop to the right from start index
  for (let i = start; i < length; i++) {
    result.push(i, length - 1 - i + start);
  }

  // loop to the left from start index
  for (let i = start - 1; i >= 0; i--) {
    result.push(i, start - i);
  }

  return result;
}
370 chars
17 lines

Here's an example usage:

index.tsx
const arr = [0, 1, 2, 3, 4, 5];
const start = 2;
const res = biDirectionalArrayIndexLooping(arr, start);

console.log(res); // [2, 3, 1, 4, 0, 5]
146 chars
6 lines

In this example, the output array [2, 3, 1, 4, 0, 5] represents the bi-directional traversal of the input array [0, 1, 2, 3, 4, 5] starting from index 2. It starts from index 2 and returns indices 3 and 1 (two indices on each side), then goes to index 3 and returns indices 4 and 0, and finally goes to index 1 and returns index 5 (the only index remaining on the other side).

gistlibby LogSnag