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
I am coming late but I have a brick to add to these good answers. I was asked to code such a function and I first did:
Array.prototype.rotate = function(n)
{
for (var i = 0; i < n; i++)
{
this.push(this.shift());
}
return this;
}
But it appeared to be less efficient than following when n
is big:
Array.prototype.rotate = function(n)
{
var l = this.length;// Caching array length before map loop.
return this.map(function(num, index) {
return this[(index + n) % l]
});
}