Skip to content

Instantly share code, notes, and snippets.

@RWOverdijk
Created May 20, 2020 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RWOverdijk/14b6f846d78d0c3573c89020fd15b100 to your computer and use it in GitHub Desktop.
Save RWOverdijk/14b6f846d78d0c3573c89020fd15b100 to your computer and use it in GitHub Desktop.
TypeScript: Tiny super basic I18n
class I18n {
public translations: TranslationsInterface;
public locale: string;
constructor(locale: string = '', translations: TranslationsInterface = {}) {
this.translations = translations;
this.locale = locale;
}
public t(key: string, params?: { [key: string]: string }) {
const translation = key.split('.').reduce((tmpMessages: any, part: string) => {
if (!tmpMessages || !tmpMessages[part]) return null;
return tmpMessages[part];
}, (this.translations[this.locale] || {}) as LanguageTranslationsInterface);
if (!translation) {
return 'ERROR: No translation for: ' + key;
}
if (!params) {
return translation;
}
return Object.keys(params).reduce((msg: string, paramKey: string) => {
return msg.replace(new RegExp(`%{${paramKey}}`, 'g'), params[paramKey]);
}, translation);
}
public toCurrency(cents: number) {
const {
decimals = 2,
unit = '$ ',
separator = '.',
delimiter = ','
} = (this.translations[this.locale]?.number as NumberTranslationsInterface | null)?.currency?.format ?? {};
return unit + (Math.round(cents) / 100)
.toFixed(decimals)
.replace('.', separator as string)
.replace(new RegExp(`\\d(?=(\\d{3})+\\${separator})`, 'g'), `$&${delimiter}`);
}
}
export interface TranslationsInterface {
[language: string]: LanguageTranslationsInterface | { number?: NumberTranslationsInterface };
}
export interface NumberTranslationsInterface {
currency: {
format: {
unit?: string,
separator?: string;
delimiter?: string;
decimals?: number;
};
};
}
export interface LanguageTranslationsInterface {
[keyOrNamespace: string]: string | LanguageTranslationsInterface;
}
const i18n = new I18n('nl', {
nl: {
number: {
currency: {
format: {
unit: '€ ',
separator: ',',
delimiter: '.',
}
}
},
hello: 'world',
nested: {
is: {
bitchin: 'word',
}
}
}
});
i18n.toCurrency(1200050);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment