Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Type-safe, generic version which mutates the array:</p> <pre><code>Array.prototype.rotate = (function() { // save references to array functions to make lookup faster var push = Array.prototype.push, splice = Array.prototype.splice; return function(count) { var len = this.length &gt;&gt;&gt; 0, // convert to uint count = count &gt;&gt; 0; // convert to int // convert count to value in range [0, len) count = ((count % len) + len) % len; // use splice.call() instead of this.splice() to make function generic push.apply(this, splice.call(this, 0, count)); return this; }; })(); </code></pre> <p>In the comments, Jean raised the issue that the code doesn't support overloading of <code>push()</code> and <code>splice()</code>. I don't think this is really useful (see comments), but a quick solution (somewhat of a hack, though) would be to replace the line</p> <pre><code>push.apply(this, splice.call(this, 0, count)); </code></pre> <p>with this one:</p> <pre><code>(this.push || push).apply(this, (this.splice || splice).call(this, 0, count)); </code></pre> <hr> <p>Using <code>unshift()</code> instead of <code>push()</code> is nearly twice as fast in Opera 10, whereas the differences in FF were negligible; the code:</p> <pre><code>Array.prototype.rotate = (function() { var unshift = Array.prototype.unshift, splice = Array.prototype.splice; return function(count) { var len = this.length &gt;&gt;&gt; 0, count = count &gt;&gt; 0; unshift.apply(this, splice.call(this, count % len, len)); return this; }; })(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload