Rotate the elements in an array in JavaScript

后端 未结 30 1827
走了就别回头了
走了就别回头了 2020-11-22 10:55

I was wondering what was the most efficient way to rotate a JavaScript array.

I came up with this solution, where a positive n rotates the array to the

30条回答
  •  我在风中等你
    2020-11-22 11:12

    @molokoloco I needed a function that I could configure to rotate in a direction - true for forward and false for backward. I created a snippet that takes a direction, a counter and an array and outputs an object with the counter incremented in the appropriate direction as well as prior, current, and next values. It does NOT modify the original array.

    I also clocked it against your snippet and although it is not faster, it is faster than the ones you compare yours with - 21% slower http://jsperf.com/js-rotate-array/7 .

    function directionalRotate(direction, counter, arr) {
      counter = direction ? (counter < arr.length - 1 ? counter + 1 : 0) : (counter > 0 ? counter - 1 : arr.length - 1)
      var currentItem = arr[counter]
      var priorItem = arr[counter - 1] ? arr[counter - 1] : arr[arr.length - 1]
      var nextItem = arr[counter + 1] ? arr[counter + 1] : arr[0]
      return {
        "counter": counter,
        "current": currentItem,
        "prior": priorItem,
        "next": nextItem
      }
    }
    var direction = true // forward
    var counter = 0
    var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
    
    directionalRotate(direction, counter, arr)
    

提交回复
热议问题