i18nUtils.ts 1.2 KB

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