Created
June 26, 2022 12:02
-
-
Save selimbat/dbdb40c621e3bd94b7ba3a534b58e1b5 to your computer and use it in GitHub Desktop.
This is a polyfill for Array.prototype.at, that landed in the spec in 2021 and that are not yet implemented by all browsers
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
if (!Array.prototype.at) { | |
Array.prototype.at = function (index) { | |
if (!this.length) return undefined; | |
let number = Number(index) || 0; // if NaN, affect 0 | |
let intIndex = Math.sign(number) * Math.floor(Math.abs(number)); | |
let relativeIndex = intIndex >= 0 ? intIndex : this.length + intIndex; | |
if (relativeIndex < 0 || relativeIndex >= this.length) return undefined; | |
return this[relativeIndex]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment