Skip to content

Instantly share code, notes, and snippets.

@SebastianHGonzalez
Created August 28, 2019 16:48
Show Gist options
  • Save SebastianHGonzalez/683b96c19d21a3ce19aad4ac15fac594 to your computer and use it in GitHub Desktop.
Save SebastianHGonzalez/683b96c19d21a3ce19aad4ac15fac594 to your computer and use it in GitHub Desktop.
import { string, shape } from "prop-types";
import es from "./messages_es";
function I18n({ id, fallback, fillers }) {
const message = es[id] || fallback || id;
const filledMessage = fillMessage(message, fillers);
if(fillTagRegex.test(filledMessage)) {
console.warn("Message missing fillers:", id);
}
return filledMessage;
}
const fillTagRegex = /\${(.*?)}/g; // it matches all tags in a string ex. '${foo}'
const fillTagCleanupRegex = /[a-zA-Z0-9]+/g; // it cleans up tag sintax ex. '${foo}' => 'foo'
/**
* Replaces string tags with values in provided as fillers
* ex. "a ${foo} is a ${baz}", { foo: "dog", baz: "canine"} => "a dog is a canine"
*
* @param {string} message
* @param {{[key: string]: string}} fillers
* @returns {string} filled message
*/
function fillMessage(message, fillers = {}) {
return (message.match(fillTagRegex) || [])
.map(fillTag => ({
fillTag,
fillerKey: fillTag.match(fillTagCleanupRegex)[0]
}))
.reduce(
(partiallyFilledMessage, { fillTag, fillerKey }) =>
partiallyFilledMessage.replace(fillTag, fillers[fillerKey] || fillTag),
message
);
}
I18n.propTypes = {
id: string.isRequired,
fallback: string,
fillers: shape({})
};
I18n.defaultProps = {
fallback: "",
fillers: {}
};
export default I18n;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment