create a function to return an left and right offset of array indexes that loop around and slice the array in a subset in javascript

Here's an example function that takes an array arr, a central index idx, and a window size size. The function returns an object with two properties - left and right. left is the index to the left of idx, while right is the index to the right of idx. If idx is at the beginning or end of arr, the offsets will "wrap around" to the other side of the array.

index.tsx
function getOffsetIndices(arr, idx, size) {
  const length = arr.length;
  const half = Math.floor(size / 2);
  let left = idx - half;
  let right = idx + half;
  
  if (left < 0) {
    left = length + left;
  }
  
  if (right >= length) {
    right = right - length;
  }
  
  return { left, right };
}
303 chars
17 lines

You can call this function with an array, an index, and a size to get the offset indices:

index.tsx
const arr = [0, 1, 2, 3, 4, 5];
const idx = 0;
const size = 4;
const offsets = getOffsetIndices(arr, idx, size);

// logs { left: 3, right: 2 }
console.log(offsets);
166 chars
8 lines

In this example, the function returns { left: 3, right: 2 } because the left offset of index 0 is index 3 (which "wraps around" to the end of the array), and the right offset is index 2. You can then use these offset indices to slice the array:

index.tsx
const subset = arr.slice(offsets.left, offsets.right + 1);

// logs [5, 0, 1, 2]
console.log(subset);
102 chars
5 lines

Here, the subset array consists of the values at indices 5, 0, 1, and 2 from the original arr array.

gistlibby LogSnag