movie-web/src/hooks/useRandomTranslation.ts

33 lines
970 B
TypeScript
Raw Normal View History

2023-10-25 16:16:25 +00:00
import { useCallback, useMemo } from "react";
2023-10-25 14:58:38 +00:00
import { useTranslation } from "react-i18next";
// 10% chance of getting a joke title
2023-12-31 15:35:10 +00:00
const shouldGiveJokeTitle = () => Math.floor(Math.random() * 10) === 0;
2023-10-25 14:58:38 +00:00
export function useRandomTranslation() {
const { t } = useTranslation();
const shouldJoke = useMemo(() => shouldGiveJokeTitle(), []);
2023-10-25 16:16:25 +00:00
const seed = useMemo(() => Math.random(), []);
2023-10-25 14:58:38 +00:00
2023-10-25 16:16:25 +00:00
const getRandomTranslation = useCallback(
(key: string): string => {
const defaultTitle = t(`${key}.default`) ?? "";
if (!shouldJoke) return defaultTitle;
2023-10-25 14:58:38 +00:00
const keys = t(`${key}.extra`, {
returnObjects: true,
defaultValue: defaultTitle,
});
if (Array.isArray(keys)) {
if (keys.length === 0) return defaultTitle;
return keys[Math.floor(seed * keys.length)];
2023-10-25 16:16:25 +00:00
}
2023-10-25 14:58:38 +00:00
return typeof keys === "string" ? keys : defaultTitle;
2023-10-25 16:16:25 +00:00
},
[t, seed, shouldJoke],
2023-10-25 16:16:25 +00:00
);
2023-10-25 14:58:38 +00:00
return { t: getRandomTranslation };
}