Guest User

Untitled

a guest
Jul 18th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. import { find, identity } from 'lodash';
  2.  
  3. const singleTagsList = new Set(['hr', 'img', 'br']);
  4.  
  5. const propertyActions = [
  6. {
  7. name: 'body',
  8. check: arg => typeof arg === 'string',
  9. process: identity,
  10. },
  11. {
  12. name: 'children',
  13. check: arg => arg instanceof Array,
  14. process: (children, f) => children.map(f),
  15. },
  16. {
  17. name: 'attributes',
  18. check: arg => arg instanceof Object,
  19. process: identity,
  20. },
  21. ];
  22.  
  23. const getPropertyAction = arg => find(propertyActions, ({check}) => check(arg));
  24.  
  25. export const parse = (data) => {
  26. const [name, ...rest] = data;
  27. const root = {
  28. name,
  29. attributes: {},
  30. body: '',
  31. children: [],
  32. };
  33.  
  34. return rest.reduce((acc, arg) => {
  35. const {name, process} = getPropertyAction(arg);
  36. return {...acc, [name]: process(arg, parse)};
  37. }, root);
  38. };
  39.  
  40. export const render = (data) => {
  41. const {
  42. name,
  43. attributes,
  44. body,
  45. children,
  46. } = data;
  47.  
  48. const attrsLine = Object.keys(attributes)
  49. .map(key => ` ${key}="${attributes[key]}"`).join('');
  50.  
  51. const content = children.length > 0 ? children.map(render).join('') : body;
  52.  
  53. return singleTagsList.has(name) ?
  54. `<${name}${attrsLine}>` :
  55. `<${name}${attrsLine}>${content}</${name}>`;
  56. };
Add Comment
Please, Sign In to add comment