Skip to content

Commit baa6c55

Browse files
authored
Merge pull request #2149 from Parvinmh/fix/language2
fix duplicate in language
2 parents cea2f31 + a9cdee3 commit baa6c55

File tree

1 file changed

+12
-30
lines changed

1 file changed

+12
-30
lines changed

src/i18n/language.ts

Lines changed: 12 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,10 @@ const languages = {
1212
fr_FR: frFR,
1313
} as const;
1414

15-
export type MessageFormat = (...args: any[]) => string;
16-
export type Message = string | MessageFormat;
17-
18-
export type Language = {
19-
[key: string]: Message | Language;
20-
};
21-
2215
export type LanguageCode = keyof typeof languages;
2316
export const DefaultLanguage = Object.keys(languages)[0] as LanguageCode;
17+
type Messages = { [key: string]: string | Messages };
2418

25-
/**
26-
* Get all available language codes
27-
*/
2819
export function getAvailableLanguages(): LanguageCode[] {
2920
return Object.keys(languages) as LanguageCode[];
3021
}
@@ -66,29 +57,20 @@ export class Translator {
6657

6758
private getString(
6859
message: string,
69-
langObj: Language = this.messages
70-
): MessageFormat | null {
71-
if (!langObj || !message) return null;
72-
73-
const splitted = message.split(".");
74-
const key = splitted[0];
75-
76-
if (langObj[key]) {
77-
const val = langObj[key];
78-
if (typeof val === "string") {
79-
return (): string => val;
80-
} else if (typeof val === "function") {
81-
return val;
82-
} else {
83-
return this.getString(splitted.slice(1).join("."), val);
84-
}
60+
obj: Messages = this.messages
61+
): string | null {
62+
const parts = message.split(".");
63+
let current: Messages | string = obj;
64+
65+
for (const part of parts) {
66+
if (typeof current !== "object" || !(part in current)) return null;
67+
current = current[part];
8568
}
8669

87-
return null;
70+
return typeof current === "string" ? current : null;
8871
}
8972

90-
translate(message: string, ...args: any[]): string {
91-
const translated = this.getString(message);
92-
return translated ? translated(...args) : message;
73+
translate(message: string): string {
74+
return this.getString(message) ?? message;
9375
}
9476
}

0 commit comments

Comments
 (0)