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
Try this :