i18nUtils.ts 992 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import {VueI18n} from "vue-i18n";
  2. import {EnumChoice, EnumChoices} from "~/types/interfaces";
  3. class I18nUtils {
  4. private i18n!: VueI18n
  5. public constructor(i18n: VueI18n) {
  6. this.i18n = i18n
  7. }
  8. /**
  9. * Return the given enum with its labels translated
  10. *
  11. * If sort is true, the enum is also sorted by its newly translated labels
  12. *
  13. * @param enum_
  14. * @param sort
  15. */
  16. public translateEnum(enum_: EnumChoices, sort: boolean = true): EnumChoices {
  17. enum_ = enum_.map(
  18. (item: EnumChoice) => {
  19. return {value: item.value, label: this.i18n.t(item.value) as string}
  20. }
  21. )
  22. if (sort) {
  23. enum_ = enum_.sort((a, b) => {
  24. if (a.label > b.label) {
  25. return 1
  26. }
  27. if (a.label < b.label) {
  28. return -1
  29. }
  30. return 0
  31. })
  32. }
  33. return enum_
  34. }
  35. }