import _get from 'lodash/get' ; export default class Translation { protected locale : string ; protected intervalRegExp : RegExp ; constructor ( locale = 'en-US' ) { this . locale = locale ; this . intervalRegExp = /^[\{\[]([^\[\]\{\}]*)[\}\]]\s?(.*)/ ; } param string protected hasIntervals ( string ) { return Boolean ( string . match ( this . intervalRegExp ) ) ; } param string param amount protected getIntervalString ( string , amount ) { const strings = string . split ( '|' ) ; const index = this . getIntervalIndex ( strings . map ( ( partial ) => { return _get ( partial . match ( this . intervalRegExp ) , 1 , '' ) ; } ) , amount ) ; string = index === false ? strings [ 0 ] : strings [ index ] ; return _get ( string . match ( this . intervalRegExp ) , 2 , string ) ; } param intervals param amount protected getIntervalIndex ( intervals , amount ) { const parsed = intervals . map ( ( interval ) => { const range = interval . replace ( /[\{\}\[\]\s]+/g , '' ) ; return range === '*' || range . indexOf ( ',' ) > - 1 ? range : parseInt ( range ) ; } ) ; for ( let index = 0 ; index < parsed . length ; index ++ ) { if ( typeof parsed [ index ] === 'string' && ( parsed [ index ] as string ) . indexOf ( ',' ) > - 1 ) { const [ from , to ] = ( parsed [ index ] as string ) . split ( ',' ) ; if ( ( to === '*' && amount >= parseInt ( from ) ) || ( from === '*' && amount <= parseInt ( to ) ) || ( amount >= parseInt ( from ) && amount <= parseInt ( to ) ) ) { return index ; } } else if ( parsed [ index ] == amount ) { return index ; } } return false ; } param strings param amount public getPlural ( string , amount ) { if ( typeof amount === 'string' ) { amount = Number ( amount ) ; } if ( ! this . hasIntervals ( string ) ) { const strings = string . split ( '|' ) ; return strings [ amount === 1 ? 0 : 1 ] || string ; } return this . getIntervalString ( string , amount ) ; } }