From 7dd6efb832494c14a365a2cd2e9f687957145e20 Mon Sep 17 00:00:00 2001 From: Kalle <38327916+Sendouc@users.noreply.github.com> Date: Fri, 10 Jun 2022 00:36:06 +0300 Subject: [PATCH] Replace Array.at with error throwing function --- app/components/Avatar.tsx | 1 + .../suggestions/comment.$tier.$userId.tsx | 3 ++- app/utils/arrays.ts | 22 +++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/app/components/Avatar.tsx b/app/components/Avatar.tsx index 0b4573a82..1e07e5557 100644 --- a/app/components/Avatar.tsx +++ b/app/components/Avatar.tsx @@ -25,6 +25,7 @@ export function Avatar({ (arr: T[], n: number) { + const result = at(arr, n); + if (result === undefined) { + throw new Error(`Index ${n} out of bounds. Array length is ${arr.length}`); + } + return result; +} + +// https://github.com/tc39/proposal-relative-indexing-method#polyfill +/** Array.at polyfill */ +function at(arr: T[], n: number) { + // ToInteger() abstract op + n = Math.trunc(n) || 0; + // Allow negative indexing from the end + if (n < 0) n += arr.length; + // OOB access is guaranteed to return undefined + if (n < 0 || n >= arr.length) return undefined; + // Otherwise, this is just normal property access + return arr[n]; +}