* Gets the translated text. Supports dot-separated nested keys; substitutes * `{param}` tokens with values from the optional `params` map.
(
key: string,
language: string = 'en',
params: Record<string, string | number> = {}
)
| 56 | * `{param}` tokens with values from the optional `params` map. |
| 57 | */ |
| 58 | function getTranslation( |
| 59 | key: string, |
| 60 | language: string = 'en', |
| 61 | params: Record<string, string | number> = {} |
| 62 | ): string { |
| 63 | const translations = loadTranslations(language) |
| 64 | |
| 65 | if (!translations) { |
| 66 | return key |
| 67 | } |
| 68 | |
| 69 | const keys = key.split('.') |
| 70 | let probe: unknown = translations |
| 71 | |
| 72 | for (const segment of keys) { |
| 73 | if (probe && typeof probe === 'object' && segment in (probe as Record<string, unknown>)) { |
| 74 | probe = (probe as Record<string, unknown>)[segment] |
| 75 | } else { |
| 76 | return key |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | if (typeof probe !== 'string') { |
| 81 | return key |
| 82 | } |
| 83 | |
| 84 | let result = probe |
| 85 | for (const [param, replacement] of Object.entries(params)) { |
| 86 | result = result.replace(new RegExp(`\\{${param}\\}`, 'g'), String(replacement)) |
| 87 | } |
| 88 | |
| 89 | return result |
| 90 | } |
| 91 | |
| 92 | function getSupportedLanguages(): string[] { |
| 93 | return [...SUPPORTED_LANGUAGES] |
no test coverage detected