Skip to content

Instantly share code, notes, and snippets.

@selimbat
Created June 26, 2022 12:02
Show Gist options
  • Save selimbat/dbdb40c621e3bd94b7ba3a534b58e1b5 to your computer and use it in GitHub Desktop.
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
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