Posted By

Leech on 07/21/06


Tagged

arrays


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

jkochis
nicolaspar


Rotate v1.1


 / Published in: JavaScript
 

URL: http://jsfromhell.com/array/rotate

Rotate the elements of an array with the minimum possible amount of movements. It's thousands faster than using sequences of "array.unshift(array.pop())" or "array.push(array.shift())". Created: 2006.01.02 - Modified: 2006.04.23

  1. /**************************************
  2. * Jonas Raoni Soares Silva
  3. * http://www.joninhas.ath.cx
  4. **************************************/
  5.  
  6. rotate = function(a, p){ //v1.1
  7. for(var l = a.length, p = (Math.abs(p) >= l && (p %= l), p < 0 && (p += l), p), i, x; p; p = (Math.ceil(l / p) - 1) * p - l + (l = p))
  8. for(i = l; i > p; x = a[--i], a[i] = a[i - p], a[i - p] = x);
  9. return a;
  10. };
  11.  
  12.  
  13.  
  14. /*
  15. Example:
  16.  
  17. <script type="text/javascript">
  18. //<![CDATA[
  19.  
  20. document.write(
  21. "rotate([1,2,3], 2) = ", rotate([1,2,3], 2), "<br />",
  22. "rotate([1,2,3], -2) = ", rotate([1,2,3], -2), "<br />",
  23. "rotate([1,2,3], 1000) = ", rotate([1,2,3], 1000), "<br />"
  24. )
  25.  
  26. //]]>
  27. </script>
  28. */

Report this snippet  

You need to login to post a comment.