Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { find, identity } from 'lodash';
- const singleTagsList = new Set(['hr', 'img', 'br']);
- const propertyActions = [
- {
- name: 'body',
- check: arg => typeof arg === 'string',
- process: identity,
- },
- {
- name: 'children',
- check: arg => arg instanceof Array,
- process: (children, f) => children.map(f),
- },
- {
- name: 'attributes',
- check: arg => arg instanceof Object,
- process: identity,
- },
- ];
- const getPropertyAction = arg => find(propertyActions, ({check}) => check(arg));
- export const parse = (data) => {
- const [name, ...rest] = data;
- const root = {
- name,
- attributes: {},
- body: '',
- children: [],
- };
- return rest.reduce((acc, arg) => {
- const {name, process} = getPropertyAction(arg);
- return {...acc, [name]: process(arg, parse)};
- }, root);
- };
- export const render = (data) => {
- const {
- name,
- attributes,
- body,
- children,
- } = data;
- const attrsLine = Object.keys(attributes)
- .map(key => ` ${key}="${attributes[key]}"`).join('');
- const content = children.length > 0 ? children.map(render).join('') : body;
- return singleTagsList.has(name) ?
- `<${name}${attrsLine}>` :
- `<${name}${attrsLine}>${content}</${name}>`;
- };
Add Comment
Please, Sign In to add comment