How to get future items and past items by specific index like in a carousel

◇◆丶佛笑我妖孽 提交于 2020-12-15 07:53:25

问题


I'm trying to create a custom carousel.
And I'm stuck with the algorithm.
I need to get future and past items by specific index.

Carousel can move around infinitely.

Example: var exampleArray = [1,2,3,4,5,6,7,8,9];

slice(exampleArray, 0); -->> currentItem = [1], futureItems = [2,3,4,5], pastItems = [6,7,8,9]
slice(exampleArray, 4); -->> currentItem = [5], futureItems = [6,7,8,9], pastItems = [1,2,3,4]
slice(exampleArray, 7); -->> currentItem = [8], futureItems = [9,1,2,3], pastItems = [4,5,6,7]


回答1:


You can use one of the solutions to this question (I like @mickmackusa's) to rotate the array to get the desired currentItem into the middle; then you can just take the slice before the middle as pastItems, the middle element as currentItem, and the slice after the middle as futureItems:

const slicer = (arr, idx) => {
  let len = arr.length;
  let mid = Math.floor(len/2);
  let rotated = arr.slice(0);
  rotated = rotated.concat(rotated.splice(0, (mid + idx + 1) % len));
  return [rotated.slice(0, mid), [rotated[mid]], rotated.slice(mid+1)]
}

const exampleArray = [1,2,3,4,5,6,7,8,9];

[pastItems, currentItem, futureItems] = slicer(exampleArray, 0);
console.log(pastItems);
console.log(currentItem);
console.log(futureItems);

[pastItems, currentItem, futureItems] = slicer(exampleArray, 4);
console.log(pastItems);
console.log(currentItem);
console.log(futureItems);

[pastItems, currentItem, futureItems] = slicer(exampleArray, 7);
console.log(pastItems);
console.log(currentItem);
console.log(futureItems);


来源:https://stackoverflow.com/questions/64817120/how-to-get-future-items-and-past-items-by-specific-index-like-in-a-carousel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!