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 right, and a negative n to the left (-length < n < length) :
Array.prototype.rotateRight = function( n ) {
this.unshift( this.splice( n, this.length ) );
}
Which can then be used this way:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
months.rotate( new Date().getMonth() );
My original version above has a flaw, as pointed out by Christoph in the comments bellow, a correct version is (the additional return allows chaining):
Array.prototype.rotateRight = function( n ) {
this.unshift.apply( this, this.splice( n, this.length ) );
return this;
}
Is there a more compact and/or faster solution, possibly in the context of a JavaScript framework? (none of the proposed versions bellow is either more compact or faster)
Is there any JavaScript framework out there with an array rotate built-in? (Still not answered by anyone)
Type-safe, generic version which mutates the array:
In the comments, Jean raised the issue that the code doesn’t support overloading of
push()andsplice(). I don’t think this is really useful (see comments), but a quick solution (somewhat of a hack, though) would be to replace the linewith this one:
Using
unshift()instead ofpush()is nearly twice as fast in Opera 10, whereas the differences in FF were negligible; the code: