## Posted By

Leech on 07/21/06

## Who likes this?

2 people have marked this snippet as a favorite

# Rotate v1.1

/ Published in: JavaScript

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

`/*************************************** Jonas Raoni Soares Silva* http://www.joninhas.ath.cx**************************************/ rotate = function(a, p){ //v1.1    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))        for(i = l; i > p; x = a[--i], a[i] = a[i - p], a[i - p] = x);    return a;};   /*Example: <script type="text/javascript">//<![CDATA[ document.write(    "rotate([1,2,3], 2) = ", rotate([1,2,3], 2), "<br />",    "rotate([1,2,3], -2) = ", rotate([1,2,3], -2), "<br />",    "rotate([1,2,3], 1000) = ", rotate([1,2,3], 1000), "<br />") //]]></script>*/`