JS rotate Array() (v15)

Revision 15 of this benchmark created by mailgpa on


Description

Function or prototype ?

Test runner

Ready to run.

Testing in
TestOps/sec
Array function rotate
var rotateArray = function(a, inc) {
  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 arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
rotateArray(arr, 5);
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 arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
arr.rotate(5);
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;

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

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
arr.rotate(5);
ready
fast
function directionalRotate(direction, counter, arr) {
  counter = direction ? (counter < arr.length - 1 ? counter + 1 : 0) : (counter > 0 ? counter - 1 : arr.length - 1)
  var currentItem = arr[counter]
  var priorItem = arr[counter - 1] ? arr[counter - 1] : arr[arr.length - 1]
  var nextItem = arr[counter + 1] ? arr[counter + 1] : arr[0]
  return {
    "counter": counter,
    "current": currentItem,
    "prior": priorItem,
    "next": nextItem
  }
}
var direction = true // forward
var counter = 0
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

directionalRotate(direction, counter, arr)
ready
stackoverflow
rotate = function(arr, count) {
  var push, splice;
  push = Array.prototype.push;
  splice = Array.prototype.splice;
  return function(count) {
    var len;
    len = this.length >>> 0;
    count = count >> 0;
    count = ((count % len) + len) % len;
    push.apply(arr, splice.call(arr, 0, count));
    return arr;
  };
};

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
var counter = 0;
rotate(arr, counter);
ready
push/shift (unshift/pop)
function arrayRotate(arr, reverse) {
  if (reverse)
    arr.push(arr.shift());
  else
    arr.unshift(arr.pop());
  return arr;
}

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
arrayRotate(arr, true);
ready

Revisions

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