Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jonas Raoni Soares Silva http://jsfromhell.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Array rotate //Javascript Function


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())" due to memory moving on the "unshift" and "shift" methods. It also doesn't use a helper array, so it's fast and requires no aditional memory.

[UPDATED CODE CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/rotate [v1.0]

rotate = function(a /*array*/, p /* integer, positive integer rotate to the right, negative to the left... */){ //v1.0
    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;
};


Usage

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 />"
)
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS