Guest User

Untitled

a guest
Dec 14th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. const {format: formatDate} = require('date-fns/fp');
  2.  
  3. const createGlot = dictionary => {
  4. const parseStrings = (lang, value, strs, exprs) => {
  5. const key = strs.map((str, i) => str + (exprs[i] || '')).join('');
  6. const found = dictionary[lang][key];
  7.  
  8. if (found === undefined) {
  9. return `~~NO GLOT FOUND FOR ${key}!!!~~`;
  10. }
  11.  
  12. if (typeof found === 'function') {
  13. return found(value);
  14. }
  15.  
  16. return found;
  17. };
  18.  
  19. const glot = options => {
  20. const {lang, value, mkFn} = options;
  21.  
  22. return (head, ...tail) => {
  23. if (Array.isArray(head)) {
  24. if (mkFn) {
  25. return mkFn(parseStrings(lang, value, head, tail));
  26. }
  27. return parseStrings(lang, value, head, tail);
  28. } else {
  29. return glot({
  30. ...options,
  31. ...head,
  32. });
  33. }
  34. };
  35. };
  36.  
  37. return glot;
  38. };
  39.  
  40. const glot = createGlot({
  41. en: {
  42. greetings: "'ello, govna'",
  43. months: date => `${date.getMonth() + 1} months`,
  44. date: 'yyyy-MM-dd',
  45. thing_1: 'number one',
  46. thing_2: 'number two',
  47. },
  48. fra: {
  49. greetings: "'sup, Monsieur",
  50. },
  51. })({lang: 'en'});
  52.  
  53. console.log(glot`greetings`);
  54. console.log(glot`INVALID_KEY`);
  55.  
  56. console.log(glot({lang: 'fra'})`greetings`);
  57. const foreverFrench = glot({lang: 'fra'});
  58. console.log(foreverFrench`greetings`);
  59.  
  60. console.log(glot({value: new Date()})`months`);
  61. console.log(glot({mkFn: formatDate})`date`(new Date()));
  62.  
  63. new Array(2).fill(null).map((_, i) => console.log(glot`thing_${i + 1}`));
Add Comment
Please, Sign In to add comment