Created
July 18, 2019 13:22
-
-
Save joelpalmer/df35691588e6aa9fdb2d1905280eb608 to your computer and use it in GitHub Desktop.
Array.prototype.swap
This file contains 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
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