langHelper.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. interface LangPair {
  2. zh: string
  3. en: string
  4. }
  5. export const langHelper = {
  6. parseLangString(str: string): LangPair {
  7. if (!str.includes('~~')) return { zh: str, en: str }
  8. const [zhPart, enPart] = str.split('~~')
  9. return {
  10. zh: zhPart.replace('zh-CN**', ''),
  11. en: enPart?.replace('en**', '') || zhPart.replace('zh-CN**', '')
  12. }
  13. },
  14. getDisplayText(str: string, currentLang: string): string {
  15. const { zh, en } = this.parseLangString(str)
  16. return currentLang === 'zh-CN' ? zh : (en || zh)
  17. },
  18. transformObject<T extends Record<string, any>>(obj: T, currentLang: string): T {
  19. if (typeof obj === 'number') { return obj }
  20. if (typeof obj === 'string') {
  21. return this.getDisplayText(obj, currentLang)
  22. }
  23. const result = { ...obj }
  24. for (const key in result) {
  25. if(Array.isArray(result[key])) {
  26. result[key] = this.transformArray(result[key], currentLang)
  27. } else if (typeof result[key] === 'string') {
  28. result[key] = this.getDisplayText(result[key], currentLang)
  29. } else if (typeof result[key] === 'object' && result[key] !== null) {
  30. result[key] = this.transformObject(result[key], currentLang)
  31. }
  32. }
  33. return result
  34. },
  35. transformArray<T extends Record<string, any>>(arr: T[], currentLang: string): T[] {
  36. return arr.map(item => this.transformObject(item, currentLang))
  37. }
  38. }