Array.prototype.move (v9)

Revision 9 of this benchmark created on


Preparation HTML

<script>
  var array = [0, 1, 2, 3, 4];
  
  Array.prototype.move1 = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
  };
  
  Array.prototype.move2 = function(pos1, pos2) {
    // local variables
    var i, tmp;
    // cast input parameters to integers
    pos1 = parseInt(pos1, 10);
    pos2 = parseInt(pos2, 10);
    // if positions are different and inside array
    if (pos1 !== pos2 && 0 <= pos1 && pos1 <= this.length && 0 <= pos2 && pos2 <= this.length) {
      // save element from position 1
      tmp = this[pos1];
      // move element down and shift other elements up
      if (pos1 < pos2) {
        for (i = pos1; i < pos2; i++) {
          this[i] = this[i + 1];
        }
      }
      // move element up and shift other elements down
      else {
        for (i = pos1; i > pos2; i--) {
          this[i] = this[i - 1];
        }
      }
      // put element from position 1 to destination
      this[pos2] = tmp;
    }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
move1
array.move1(1, 4);
array.move1(0, 2);
ready
move2
array.move2(1, 4);
array.move2(0, 2);
ready

Revisions

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