Created
October 23, 2014 07:04
-
-
Save Orbifold/63e5f14d81bb09009636 to your computer and use it in GitHub Desktop.
Move an item in place in an array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.move = function (pos1, pos2) { | |
var i, tmp; | |
pos1 = parseInt(pos1, 10); | |
pos2 = parseInt(pos2, 10); | |
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; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment