'Creating breadcrumbs from a link tree with DFS in JavaScript
I am struggling to write a DFS algorithm in JavaScript to create breadcrumbs for a link tree. Given the below input of linkItems and expected output that I am console logging, I've only gotten the first couple of levels to work. What am I missing?
const linkItems = {
id: "a",
links: [
{
id: "b",
links: [
{
id: "c"
}
]
},
{
id: "d",
links: [{
id: "e",
links: [
{
id: "f"
}
]
},
{
id: "g"
}]
}
]
};
const flattenLinkItems = (id, root) => {
if (!root) return null;
let node = null;
let acc = [];
let q = [];
q.push(root);
while (q.length > 0) {
node = q.shift();
if (node.links) {
const { links, ...item } = node;
acc.push(item.id)
if (item.id === id) {
q = [];
return acc
}
q = links;
} else {
acc.push(node.id)
if (node.id === id) {
q = [];
return acc
} else {
}
}
}
return acc;
}
let findThis = []
// given id of...
// ... c will return ['a','b','c']
findThis = flattenLinkItems("c", linkItems);
console.log("given c", findThis);
// d will return ['a','d']
findThis = flattenLinkItems("d", linkItems);
console.log("given d", findThis);
// f will return ['a','d','e','f']
findThis = flattenLinkItems("f", linkItems);
console.log("given f", findThis);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
