-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslation-proxy.ts
39 lines (38 loc) · 1.3 KB
/
translation-proxy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Creates a translator object that allows for dynamic translation of keys.
*
* @param {Object} translations - An object containing key-value pairs of translations.
* @returns {Proxy} A proxy object that allows for dynamic translation of keys.
*/
class Translator {
constructor(private translations: { [key: string]: string }) {
return new Proxy(this, {
/**
* Returns the translation for a given key.
*
* @param {Object} target - The target object.
* @param {string} prop - The key to translate.
* @returns {string} The translated value or a fallback message if not found.
*/
get(target: Translator, prop: string): string {
return target.translations[prop] || `Translation not found for key: ${prop}`;
}
});
}
}
// Usage example:
/**
* Usage example: translating HTML elements with data-translate attribute.
*
* @example
* const translations = new Translator({
* hello: 'Привіт',
* goodbye: 'До побачення'
* // other translations...
* });
*
* document.querySelectorAll('[data-translate]').forEach((element: HTMLElement) => {
* const key: string = element.dataset.translate;
* element.innerHTML = translations[key];
* });
*/