JS rotate Array()

Benchmark created by molokoloco on


Description

Function or prototype ?

Test runner

Ready to run.

Testing in
TestOps/sec
Array function rotate
var rotateArray = function(a, inc) { // var b = rotateArray([1,2,3], -1) // Faster than // "array.unshift(array.pop())" or "array.push(array.shift())". 
    for (var l = a.length, inc = (Math.abs(inc) >= l && (inc %= l), inc < 0 && (inc += l), inc), i, x; inc; inc = (Math.ceil(l / inc) - 1) * inc - l + (l = inc))
    for (i = l; i > inc; x = a[--i], a[i] = a[i - inc], a[i - inc] = x);
    return a;
};

var array = ['a','b','c','d','e','f','g','h','i'];

console.log(array);
console.log(rotateArray(array.slice(), -1) ); // Clone array with slice()
ready
Array prototype rotate
Array.prototype.rotate = (function() {
    return function(inc) {
        for (var l = this.length, inc = (Math.abs(inc) >= l && (inc %= l), inc < 0 && (inc += l), inc), i, x; inc; inc = (Math.ceil(l / inc) - 1) * inc - l + (l = inc))
        for (i = l; i > inc; x = this[--i], this[i] = this[i - inc], this[i - inc] = x);
        return this;
    };
})();

var array2 = ['a','b','c','d','e','f','g','h','i'];

console.log(array2);
console.log(array2.slice().rotate(1)); // Clone array with slice()
ready
Array prototype rotate with unshift/splice
Array.prototype.rotate = (function() {
    var unshift = Array.prototype.unshift,
        splice = Array.prototype.splice;

    return function(count) {
        var len = this.length >>> 0,
            count = count >> 0;

        unshift.apply(this, splice.call(this, count % len, len));
        return this;
    };
})();

var array3 = ['a','b','c','d','e','f','g','h','i'];

console.log(array3);
console.log(array3.slice().rotate(1)); // Clone array with slice()
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.