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
@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)