Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,47 @@ const food = {
const tree = document.querySelector('#tree');

function createTree(element, data) {
// WRITE YOUR CODE HERE
const ul = document.createElement('ul');

for (const key in data) {
const li = document.createElement('li');
li.textContent = key;

const children = createSubTree(data[key]);

if (children) {
li.appendChild(children);
}

ul.appendChild(li);
}

element.appendChild(ul);
}
Comment on lines 23 to +40
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic inside this for...in loop (lines 26-37) is almost identical to the logic inside the forEach loop in the createSubTree function (lines 51-62). This is code duplication.

The createSubTree function is already capable of building the entire tree structure. You can simplify this createTree function to just call createSubTree(data) and then append the resulting <ul> element to the element container. This avoids repeating code and makes the recursive nature of the solution clearer.


function createSubTree(obj) {
const keys = Object.keys(obj);

if (!keys.length) {
return null;
}

const ul = document.createElement('ul');

keys.forEach(key => {
const li = document.createElement('li');
li.textContent = key;

const children = createSubTree(obj[key]);

if (children) {
li.appendChild(children);
}

ul.appendChild(li);
});

return ul;
}

createTree(tree, food);
Loading