Skip to content

Instantly share code, notes, and snippets.

@beardlessman
Created May 24, 2019 13:09
Show Gist options
  • Save beardlessman/2eca0b2d1c6606d9c7bc0986a6c23a4d to your computer and use it in GitHub Desktop.
Save beardlessman/2eca0b2d1c6606d9c7bc0986a6c23a4d 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 => propertyActions.find(({ 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('');
};
const data = [
'html',
[
['head', [['title', 'hello, hexlet!']]],
[
'body',
{ class: 'container' },
[
['h1', { class: 'header' }, 'html builder example'],
['div', [['span'], ['span', { class: 'text', id: 'uniq-key' }]]]
]
]
]
];
console.log(buildHtml(data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment