Created
April 27, 2018 08:29
-
-
Save tuor4eg/21cc6b4ced17e51aa1021964a0572280 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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