skip to Main Content

I am working on a circular carousel. Given an array of n items, n>6 in my case, i want to calculate all the items within the array that are less than or equal to 3 positions away from a particular index (currentIndex) in a circular fashion e.g.

//  currentIndex = 0
//  i       0    1    2    3    4    5    6    7    8    9   
// --------------------------------------------------------
// offset   0   +1   +2   +3   +3   +3   +3   -3   -2   -1

In the above example, 0 is the currentIndex. Indices 1,2,3 are within currentIndex + 3 places. Also, indices 7, 8, 9 are also within currentIndex – 3 positions in a circular fashion. All other indices that lie out side the range are considered to be of value 3. These positive and negative values will ultimately map to positions on the screen.

I have written the following function to calculate the offset position of a given index relative to a currentIndex

function getOffset(currentIndex: number, index: number, length: number) {
  const diff = index - currentIndex;

  if (diff === 0) {
    return 0;
  } else if (diff < 0) {
    if (diff < -3) {
      return Math.min(length - currentIndex + index, 3);
    } else {
      return Math.min(diff, 3);
    }
  } else {
    if (diff < length - 3) {
      return Math.min(diff, 3);
    } else {
      return Math.max(diff - length, -3);
    }
  }
}

// getOffset(0, 0, 10) -> 0
// getOffset(0, 1, 10) -> 1
// getOffset(0, 9, 10) -> -1
// getOffset(0, 6, 10) -> 3

This algorithm works but is verbose. Is there a simpler way to do this?

2

Answers


  1. Try this :

    function getOffset(currentIndex, index, length) {
      const diff = (index - currentIndex + length) % length;
      if (diff <= 3) {
        return diff;
      } else if (diff >= length - 3) {
        return diff - length;
      } else {
        return 3;
      }
    }
    
    Login or Signup to reply.
  2. def f(i,j,n)
      ans = [(j-i)%n, (i-j)%n, 3].min
      ans *= -1 if (j - i) >= 3 && ans == (i-j) % n
      return ans
    end
    
    => :f
    > f(0,0,10)
    => 0
    > f(0,1,10)
    => 1
    > f(0,9,10)
    => -1
    > f(0,6,10)
    => 3
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search