Skip to content

Commit

Permalink
fix: add polyfill for Array.prototype.at (#2752)
Browse files Browse the repository at this point in the history
* fix: add polyfill for Array.prototype.at

* fix: ts errors
  • Loading branch information
isekovanic authored Nov 4, 2024
1 parent 0a4c852 commit c5a3046
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions package/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/** i18next polyfill to handle intl format for pluralization. For more info see https://www.i18next.com/misc/json-format#i-18-next-json-v4 */
import 'intl-pluralrules';
import './polyfills';

export * from './components';
export * from './hooks';
Expand Down
28 changes: 28 additions & 0 deletions package/src/polyfills.ts
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,
});
}
})();

0 comments on commit c5a3046

Please sign in to comment.