Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const {format: formatDate} = require('date-fns/fp');
- const createGlot = dictionary => {
- const parseStrings = (lang, value, strs, exprs) => {
- const key = strs.map((str, i) => str + (exprs[i] || '')).join('');
- const found = dictionary[lang][key];
- if (found === undefined) {
- return `~~NO GLOT FOUND FOR ${key}!!!~~`;
- }
- if (typeof found === 'function') {
- return found(value);
- }
- return found;
- };
- const glot = options => {
- const {lang, value, mkFn} = options;
- return (head, ...tail) => {
- if (Array.isArray(head)) {
- if (mkFn) {
- return mkFn(parseStrings(lang, value, head, tail));
- }
- return parseStrings(lang, value, head, tail);
- } else {
- return glot({
- ...options,
- ...head,
- });
- }
- };
- };
- return glot;
- };
- const glot = createGlot({
- en: {
- greetings: "'ello, govna'",
- months: date => `${date.getMonth() + 1} months`,
- date: 'yyyy-MM-dd',
- thing_1: 'number one',
- thing_2: 'number two',
- },
- fra: {
- greetings: "'sup, Monsieur",
- },
- })({lang: 'en'});
- console.log(glot`greetings`);
- console.log(glot`INVALID_KEY`);
- console.log(glot({lang: 'fra'})`greetings`);
- const foreverFrench = glot({lang: 'fra'});
- console.log(foreverFrench`greetings`);
- console.log(glot({value: new Date()})`months`);
- console.log(glot({mkFn: formatDate})`date`(new Date()));
- new Array(2).fill(null).map((_, i) => console.log(glot`thing_${i + 1}`));
Add Comment
Please, Sign In to add comment