methods/i18n.js

  1. import { DEFAULT_LANG } from './../lib/constants'
  2. import _config from './../lib/config'
  3. /**
  4. * @method
  5. * @memberof ecomUtils
  6. * @name i18n
  7. * @description Get translated string by lang code from dictionary object.
  8. * @param {object} dictionary - Dictionary object containing string in multiple langs
  9. * @param {string} [lang=$ecomConfig.get('lang')] - Snake case language code, eg.: 'en_us', 'pt_br'
  10. * @returns {string|object}
  11. *
  12. * @example
  13. * // With simple dictionary objects
  14. * ecomUtils.i18n({ en_us: 'Hello', pt_br: 'Olá' })
  15. * // => 'Hello'
  16. * ecomUtils.i18n({ en_us: 'Hello', pt_br: 'Olá' }, 'pt_br')
  17. * // => 'Olá'
  18. *
  19. * @example
  20. * // With nested objects
  21. * ecomUtils.i18n({ hello: { en_us: 'Hello', pt_br: 'Olá' }})
  22. * // => { hello: 'Hello' }
  23. * ecomUtils.i18n({ hello: { en_us: 'Hello', pt_br: 'Olá' }, world: { en_us: 'World' }}, 'pt_br')
  24. * // => { hello: 'Olá', world: 'World' }
  25. * ecomUtils.i18n({ en_us: { hello: 'Hello', world: 'World' }, pt_br: { hello: 'Olá' }}, 'pt_br')
  26. * // => { hello: 'Olá' }
  27. *
  28. * @example
  29. * // You can also set the configured lang first
  30. * $ecomConfig.set('lang', 'pt_br')
  31. * // Then call `i18n` without expliciting lang
  32. * ecomUtils.i18n({ en_us: 'Hello', pt_br: 'Olá' })
  33. * // => Olá
  34. */
  35. const i18n = (dictionary, lang = _config.get('lang')) => {
  36. if (typeof dictionary === 'object' && dictionary !== null) {
  37. const prop = Object.keys(dictionary)[0]
  38. if (/^[a-z]{2}(_[a-z]{2})?$/.test(prop)) {
  39. // supposed to be object of languages options
  40. return dictionary[lang] || dictionary[DEFAULT_LANG] || dictionary[prop]
  41. } else {
  42. // recursive
  43. const localDictionary = Array.isArray(dictionary) ? [] : {}
  44. for (const prop in dictionary) {
  45. if (dictionary[prop] !== undefined) {
  46. localDictionary[prop] = i18n(dictionary[prop], lang)
  47. }
  48. }
  49. return localDictionary
  50. }
  51. }
  52. return dictionary
  53. }
  54. export default i18n