@hackplan/polaris
Version:
Shopify’s product component library
21 lines (20 loc) • 773 B
JavaScript
import { get } from '../../../../utilities/get';
const REPLACE_REGEX = /{([^}]*)}/g;
export default 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;
}