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
n
function rotate(arr, k) { for (var i = 0; i < k+1; i++) { arr.push(arr.shift()); } return arr; } //k work as an index array console.log(rotate([1, 2, 7, 4, 5, 6, 7], 3)); //[5,6,7,1,2,7,4] console.log(rotate([-1, -100, 3, 99], 2)); //[99,-1,-100,3]