1
0
Fork 0
mirror of https://github.com/movie-web/movie-web.git synced 2025-03-05 02:56:06 +00:00
movie-web/src/hooks/useRandomTranslation.ts

30 lines
895 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
const shouldGiveJokeTitle = () => Math.floor(Math.random() * 10) === 0;
2023-10-25 14:58:38 +00:00
export function useRandomTranslation() {
const { t } = useTranslation();
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 shouldRandom = shouldGiveJokeTitle();
const defaultTitle = t(`${key}.default`) ?? "";
if (!shouldRandom) return defaultTitle;
2023-10-25 14:58:38 +00:00
const keys = t(`${key}.extra`, { returnObjects: true });
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]
);
2023-10-25 14:58:38 +00:00
return { t: getRandomTranslation };
}