Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Created July 18, 2018 08:12
Show Gist options
  • Select an option

  • Save YozhEzhi/6578e3fe23af1948b607d2c27ca87840 to your computer and use it in GitHub Desktop.

Select an option

Save YozhEzhi/6578e3fe23af1948b607d2c27ca87840 to your computer and use it in GitHub Desktop.
Abstract syntax tree.
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}>`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment