Array.prototype.move (v13)

Revision 13 of this benchmark created on


Preparation HTML

<script>
  var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
  
  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(3, 88);
array.move1(77, 43);
ready
move2
array.move2(3, 88);
array.move2(77, 43);
ready

Revisions

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