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 would probably do something like this:
Array.prototype.rotate = function(n) {
return this.slice(n, this.length).concat(this.slice(0, n));
}
Edit Here’s a mutator version:
Array.prototype.rotate = function(n) {
while (this.length && n < 0) n += this.length;
this.push.apply(this, this.splice(0, n));
return this;
}