From c5a3046c8612581b6beaa9ed88a05925fb043a11 Mon Sep 17 00:00:00 2001 From: Ivan Sekovanikj <31964049+isekovanic@users.noreply.github.com> Date: Mon, 4 Nov 2024 12:29:23 +0100 Subject: [PATCH] fix: add polyfill for Array.prototype.at (#2752) * fix: add polyfill for Array.prototype.at * fix: ts errors --- package/src/index.ts | 1 + package/src/polyfills.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 package/src/polyfills.ts diff --git a/package/src/index.ts b/package/src/index.ts index 9c4c8156f8..ca51f9ec0f 100644 --- a/package/src/index.ts +++ b/package/src/index.ts @@ -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'; diff --git a/package/src/polyfills.ts b/package/src/polyfills.ts new file mode 100644 index 0000000000..55f82860bf --- /dev/null +++ b/package/src/polyfills.ts @@ -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, + }); + } +})();