Skip to content

Instantly share code, notes, and snippets.

@tuor4eg
Last active April 26, 2018 14:51
Show Gist options
  • Save tuor4eg/4b5f983155c5f2cbe66973faf3407546 to your computer and use it in GitHub Desktop.
Save tuor4eg/4b5f983155c5f2cbe66973faf3407546 to your computer and use it in GitHub Desktop.
const getAttr = (attrib) => {
if (attrib.length === 0) {
return [];
}
const keys = Object.keys(attrib);
return keys.map(element => ` ${element}="${attrib[element]}"`).join('');
};
const makeObj = {
tag: [],
attributes: [],
children: [],
content: [],
};
const checkChildren = children => children.map(node => buildHtml(node)).join('');
const buildHtml = (model) => {
const html = model.reduce((acc, element, index) => {
if (typeof element === 'string' && index === 0) {
return { ...acc, tag: [element] };
}
if (typeof element === 'string') {
return { ...acc, content: [element] };
}
if (element instanceof Array) {
const newChildren = [...acc.children, element];
return { ...acc, children: newChildren };
}
return { ...acc, attributes: element };
}, makeObj);
if (html.tag.length === 0) {
return checkChildren(html.children);
}
const getOpenTag = `<${html.tag}${getAttr(html.attributes)}>`;
const getCloseTag = `${html.content}</${html.tag}>`;
const getChildren = (html.children.length === 0) ? [] : checkChildren(html.children);
const makeString = `${getOpenTag}${getChildren}${getCloseTag}`;
return makeString;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment