polyfill.ts 623 B

123456789101112131415161718192021222324252627
  1. declare global {
  2. interface Array<T> {
  3. at(index: number): T | undefined;
  4. }
  5. }
  6. if (!Array.prototype.at) {
  7. Array.prototype.at = function (index: number) {
  8. // Get the length of the array
  9. const length = this.length;
  10. // Convert negative index to a positive index
  11. if (index < 0) {
  12. index = length + index;
  13. }
  14. // Return undefined if the index is out of range
  15. if (index < 0 || index >= length) {
  16. return undefined;
  17. }
  18. // Use Array.prototype.slice method to get value at the specified index
  19. return Array.prototype.slice.call(this, index, index + 1)[0];
  20. };
  21. }
  22. export {};