mirror of
https://github.com/Sendouc/sendou.ink.git
synced 2026-10-01 15:48:23 -05:00
Replace Array.at with error throwing function
This commit is contained in:
@@ -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"
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user