Rotate //JavaScript Repository

Description

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

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/rotate [rev. #2]

rotate = function(a, p){
    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 (Example)

<script type="text/javascript">
//<![CDATA[

document.write(
    "rotate([1,2,3], 2) = ".bold(), rotate([1,2,3], 2), "<br />",
    "rotate([1,2,3], -2) = ".bold(), rotate([1,2,3], -2), "<br />",
    "rotate([1,2,3], 1000) = ".bold(), rotate([1,2,3], 1000), "<br />"
)

//]]>
</script>

Help

rotate(vector: Array, rotateBy: Integer): Array
Rotates the array elements to the left or right and, returns the own array.
vector
array to be rotated
rotateBy
specifies how many positions the array should be rotated by, negative values rotate to the left and positive ones to the right

Rank (Votes: 62)

2.56