12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- interface LangPair {
- zh: string
- en: string
- }
- export const langHelper = {
- parseLangString(str: string): LangPair {
- if (!str.includes('~~')) return { zh: str, en: str }
- const [zhPart, enPart] = str.split('~~')
- return {
- zh: zhPart.replace('zh-CN**', ''),
- en: enPart?.replace('en**', '') || zhPart.replace('zh-CN**', '')
- }
- },
- getDisplayText(str: string, currentLang: string): string {
- const { zh, en } = this.parseLangString(str)
- return currentLang === 'zh-CN' ? zh : (en || zh)
- },
- transformObject<T extends Record<string, any>>(obj: T, currentLang: string): T {
- if (typeof obj === 'number') { return obj }
- if (typeof obj === 'string') {
- return this.getDisplayText(obj, currentLang)
- }
- const result = { ...obj }
- for (const key in result) {
- if(Array.isArray(result[key])) {
- result[key] = this.transformArray(result[key], currentLang)
- } else if (typeof result[key] === 'string') {
- result[key] = this.getDisplayText(result[key], currentLang)
- } else if (typeof result[key] === 'object' && result[key] !== null) {
- result[key] = this.transformObject(result[key], currentLang)
- }
- }
- return result
- },
- transformArray<T extends Record<string, any>>(arr: T[], currentLang: string): T[] {
- return arr.map(item => this.transformObject(item, currentLang))
- }
- }
|