-
Notifications
You must be signed in to change notification settings - Fork 326
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: add polyfill for Array.prototype.at (#2752)
* fix: add polyfill for Array.prototype.at * fix: ts errors
- Loading branch information
1 parent
0a4c852
commit c5a3046
Showing
2 changed files
with
29 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
(function () { | ||
if (!Array.prototype.at) { | ||
// eslint-disable-next-line no-extend-native | ||
Object.defineProperty(Array.prototype, 'at', { | ||
configurable: true, | ||
enumerable: false, | ||
value: function at(index: number) { | ||
// Convert to integer if index is not provided | ||
const len = this.length; | ||
let relativeIndex = Number(index) || 0; | ||
|
||
// Handle negative indices | ||
if (relativeIndex < 0) { | ||
relativeIndex += len; | ||
} | ||
|
||
// Return undefined if index is out of bounds | ||
if (relativeIndex < 0 || relativeIndex >= len) { | ||
return undefined; | ||
} | ||
|
||
// Return the element at the calculated index | ||
return this[relativeIndex]; | ||
}, | ||
writable: true, | ||
}); | ||
} | ||
})(); |