Replace Array.at with error throwing function

This commit is contained in:
Kalle
2022-06-10 00:36:06 +03:00
parent 5755b06756
commit 7dd6efb832
3 changed files with 25 additions and 1 deletions

View File

@@ -25,6 +25,7 @@ export function Avatar({
<img
className={clsx("avatar", className)}
src={
// xxx: picture src offer png fallback
discordAvatar
? `https://cdn.discordapp.com/avatars/${discordId}/${discordAvatar}.webp${
size === "lg" ? "" : "?size=80"

View File

@@ -13,6 +13,7 @@ import {
canAddCommentToSuggestionBE,
canAddCommentToSuggestionFE,
} from "~/permissions";
import { atOrError } from "~/utils/arrays";
import { parseRequestFormData, requireUser, validate } from "~/utils/remix";
import { PLUS_SUGGESTIONS_PAGE } from "~/utils/urls";
import { actualNumber } from "~/utils/zod";
@@ -60,7 +61,7 @@ export default function PlusCommentModalPage() {
const user = useUser();
const matches = useMatches();
const params = useParams();
const data = matches.at(-2)!.data as PlusSuggestionsLoaderData;
const data = atOrError(matches, -2).data as PlusSuggestionsLoaderData;
const targetUserId = Number(params.userId);
const tierSuggestedTo = String(params.tier);

View File

@@ -2,3 +2,25 @@
export function allTruthy(arr: unknown[]) {
return arr.every(Boolean);
}
/** Mimics Array.prototype.at except throws an error if index out of bounds */
export function atOrError<T>(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<T>(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];
}