langHelper.ts 1.6 KB

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