import { formatString } from './utils' ; const localeCodeRegex = /^([a-z]{2})-([A-Z]{2})$/ ; export type LocaleType = 'en-US' | 'ja-JP' | 'fr-FR' ; type formatterFunction = ( args ? : object ) => string ; class Translation { param value { string } param resource { string } param namespace { string } private static translate ( value , resource , namespace ) { return resource ? Translation . getResource ( resource , namespace ) [ value ] || value : value ; } private static getResource = ( resource , namespace ) : JSON => ( namespace ? resource [ namespace ] : resource ) ; private locale : LocaleType = 'en-US' ; private loadedResources : object = { } ; param locale public setLocale ( locale ) { const localeMatch = locale . match ( localeCodeRegex ) ; if ( ! locale && ( ! localeMatch || localeMatch . length < 1 ) ) { return ; } this . locale = locale ; } return public getLocale ( ) { return this . locale ; } param value { string } param namespace { string } example returns public t ( value , namespace ? ) { return ( args ? ) : string => { if ( this . loadedResources && this . loadedResources [ this . locale ] ) { return formatString ( Translation . translate ( value , this . loadedResources [ this . locale ] , namespace ) , args ) ; } const resource = this . loadResource ( this . locale ) ; return formatString ( Translation . translate ( value , resource , namespace ) || value , args ) ; } ; } param locale { LocaleType } param resource { JSON } public setResource ( locale , resource ) { this . locale = locale ; this . loadedResources = resource ; } param locale private loadResource ( locale ) { return this . loadedResources [ locale ] ; } } const i18n = new Translation ( ) ; export { i18n } ;