UNPKG

@hackplan/polaris

Version:

Shopify’s product component library

39 lines (38 loc) 1.3 kB
import { get } from '../get'; import { merge } from '../merge'; const REPLACE_REGEX = /{([^}]*)}/g; export class I18n { constructor(translation) { this.translation = translation; this.translate = (id, replacements) => { return translate(id, this.translation, replacements); }; this.setTranslation(translation); } setTranslation(translation) { this.translation = Array.isArray(translation) ? merge(...translation) : translation; } translationKeyExists(path) { return Boolean(get(this.translation, path)); } } export function translate(id, translations, replacements) { const text = get(translations, id); if (!text) { return ''; } if (replacements) { return text.replace(REPLACE_REGEX, (match) => { const replacement = match.substring(1, match.length - 1); if (!replacements.hasOwnProperty(replacement)) { throw new Error(`No replacement found for key '${replacement}'. The following replacements were passed: ${Object.keys(replacements) .map((key) => `'${key}'`) .join(', ')}`); } return replacements[replacement]; }); } return text; }