Skip to content

Instantly share code, notes, and snippets.

@sranso
Created October 3, 2016 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sranso/85f6ded573088e5cf5f5780e5b88a7f7 to your computer and use it in GitHub Desktop.
Save sranso/85f6ded573088e5cf5f5780e5b88a7f7 to your computer and use it in GitHub Desktop.
// 1. describe virtual dom
// (as obj / list; start with list, expand as nec)
// node : obj attributes : list html
const rootNode = [
'div', {
'style': {
'textAlign': 'center',
'color': 'blue',
'margin': '20px'
}
},
['hello world']
];
const nestedNode = [
'div', {
'style': {
'textAlign': 'center',
'color': 'blue',
'margin': '20px'
}
},
[
'p', {
'style': {
'color': 'black'
}
},
['hello world']
]
];
// 2. and take it to real dom (convert to html)
const render = (node) => {
if (node.length !== 3) {
throw new Error('Please pass a valid node.');
}
return parseNode(node);
};
const parseNode = (node, isTextNode = false) => {
const elType = node[0];
return node.reduce((acc, el, index) => {
if (isTextNode) {
return `${acc}${el}`;
} else if (index === 0) {
return `${acc}<${elType}`;
} else if (Array.isArray(el)) {
// handle children
if (el.length > 1) {
return `${acc}${parseNode(el)}</${elType}>`;
} else {
return `${acc}${parseNode(el, true)}</${elType}>`;
}
} else if (!Array.isArray(el) && typeof el === 'object') {
// handle styles
const styles = parseStyles(el);
return `${acc} ${styles}>`;
} else {
// handle ??? nothing goes here rn
return acc;
}
}, '');
};
const parseStyles = (stylesNode) => {
if (!stylesNode.hasOwnProperty('style')) {
throw new Error('Please pass a valid styles node.');
}
const styles = Object.keys(stylesNode.style).map((key) => {
return `${key}: ${stylesNode.style[key]}`;
});
return `style="${styles.join('; ')}"`;
};
const app = document.getElementById('app');
console.log(render(nestedNode));
console.log(render(rootNode));
app.innerHTML = render(nestedNode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment