Skip to content

Instantly share code, notes, and snippets.

@ArnonEilat
Last active December 29, 2015 16:29
Show Gist options
  • Save ArnonEilat/7697883 to your computer and use it in GitHub Desktop.
Save ArnonEilat/7697883 to your computer and use it in GitHub Desktop.
Array.prototype.js
Array.prototype.insert = function(index, item) {
this.splice(index, 0, item);
};
/***
* var swapTest=['a','b','c'];
* swapTest.swap('a','c')
* @param {type} first
* @param {type} second
* @returns {undefined}
*/
Array.prototype.swap = function(first, second) {
var firstIdx;
var secondIdx;
for (var i = 0; i < this.length; i++) {
if (this[i] === first) {
firstIdx = i;
break;
}
}
for (var i = 0; i < this.length; i++) {
if (this[i] === second) {
secondIdx = i;
break;
}
}
if (firstIdx === undefined || secondIdx === undefined)
throw "Swap Exception";
var tmp = this[firstIdx];
this[firstIdx] = this[secondIdx];
this[secondIdx] = tmp;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment