Skip to content

Instantly share code, notes, and snippets.

@tuor4eg
Created April 27, 2018 08:29
Show Gist options
  • Save tuor4eg/21cc6b4ced17e51aa1021964a0572280 to your computer and use it in GitHub Desktop.
Save tuor4eg/21cc6b4ced17e51aa1021964a0572280 to your computer and use it in GitHub Desktop.
const propertyActions = [
{
name: 'body',
check: arg => typeof arg === 'string',
},
{
name: 'children',
check: arg => arg instanceof Array,
},
{
name: 'attributes',
check: arg => arg instanceof Object,
},
];
const getPropertyAction = arg => _.find(propertyActions, ({ check }) => check(arg));
const buildAttrString = attrs =>
Object.keys(attrs).map(key => ` ${key}="${attrs[key]}"`).join('');
const buildHtml = (data) => {
const [first, ...rest] = data;
const root = {
name: first,
attributes: {},
body: '',
children: [],
};
const tag = rest
.reduce((acc, arg) => {
const { name } = getPropertyAction(arg);
return { ...acc, [name]: arg };
}, root);
return [`<${tag.name}${buildAttrString(tag.attributes)}>`,
`${tag.body}${tag.children.map(buildHtml).join('')}`,
`</${tag.name}>`,
].join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment