So I need a function that converts a js object of type:
{node: 'X', children: [{node: 'Y'}]}
with any depth into a string that is similar to html. For example the above should be converted into something like:
'<div class="X"><div class="Y"></div></div>'
This should be intuitive in a way that the order nodes are inserted into each other is same divs are. So here is what I have this far:
function convertObj(obj){
const html_start = '<div class="';
const html_end = '</div>';
let current_parent = obj;
let child_nodes = '';
console.log(current_parent, current_parent.children)
if( typeof( current_parent.children)!= 'undefined'){
let childrn = current_parent.children.map(child_node => convertObj(child_node) )
child_nodes = child_nodes + childrn
}
return html_start+current_parent.node+'">'+child_nodes+html_end;
}
The problem is , between child nodes if they are multiple in number.
And here is my jest test, which is failing
describe('convertObj', () => {
it('should turn node value to a div with class of the same name', () => {
expect(convertObj({node: 'A'})).toBe('<div class="A"></div>');
});
it('should incert nodes in children to parent node', () => {
expect(convertObj({node: 'A', children:[{node : 'B'}]})).toBe('<div class="A"><div class="B"></div></div>');
expect(convertObj({node: 'A', children:[{node : 'B'}, {node: 'C', children: [{node: 'D'}]}]})).toBe('<div class="A"><div class="B"></div> <div class="C"><div class="D"></div></div></div>');
});
});
Help appreciated! You can run tests here
.join()on the array. Replace the implicit call with an explicit one with the proper settings.