Skip to content

Instantly share code, notes, and snippets.

@joelpalmer
Created July 18, 2019 13:22
Show Gist options
  • Save joelpalmer/df35691588e6aa9fdb2d1905280eb608 to your computer and use it in GitHub Desktop.
Save joelpalmer/df35691588e6aa9fdb2d1905280eb608 to your computer and use it in GitHub Desktop.
Array.prototype.swap
if (!Array.prototype.swap) {
Object.defineProperty(Array.prototype, 'swap', {
value: function (idxA, idxB) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
const o = Object(this);
const len = o.length >>> 0;
if (len === 0) {
return false;
}
if (typeof idxA !== 'number') {
throw new TypeError('idxA must be a number')
}
if (typeof idxB !== 'number') {
throw new TypeError('idxB must be a number')
}
const temp = o[idxA];
o[idxA] = o[idxB];
o[idxB] = temp;
}
})
}
// let arr = [1,2,3,4,5,6,7];
// arr.swap(6, 2);
// arr;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment