-
Notifications
You must be signed in to change notification settings - Fork 0
/
translation-proxy.js
47 lines (46 loc) · 1.41 KB
/
translation-proxy.js
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
40
41
42
43
44
45
46
47
/**
* 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.
*
* @example
* const translations = new Translator({
* hello: 'Привіт',
* goodbye: 'До побачення'
* // other translations...
* });
*/
class Translator {
constructor(translations) {
this.translations = translations;
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, prop) {
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 => {
* const key = element.dataset.translate;
* element.innerHTML = translations[key];
* });
*/