Skip to content

Instantly share code, notes, and snippets.

@daneharrigan
Last active June 16, 2017 02:44
Show Gist options
  • Save daneharrigan/55a2ce5dfb799446e3c58d4fa63ffb53 to your computer and use it in GitHub Desktop.
Save daneharrigan/55a2ce5dfb799446e3c58d4fa63ffb53 to your computer and use it in GitHub Desktop.
const dataset = [
{
"key":'a',
"children": [
{
"key":'a1',
"children": [
{
"key":'a1a',
"children": [],
},
{
"key":'a1b',
"children": [],
},
],
},
{
"key":'a2',
"children": [
{
"key":'a2a',
"children":[
{
"key":'a2a1',
"children": [],
},
]
},
{
"key":'a2b',
"children": [],
},
],
},
{
"key":'a3',
"children": [
{
"key":'a3a',
"children": [],
},
{
"key":'a3b',
"children": [
{
"key":'a3b1',
"children": [],
},
],
},
],
},
],
},
{
"key":'b',
"children": [],
},
];
function bfs(parentRoute, dataset, target) {
const nextNodes = [];
for (node of dataset) {
const { key, children } = node;
const route = parentRoute.slice();
route.push(node.key);
if (key === target) {
return route;
}
if (children) {
nextNodes.push(() => bfs(route, children, target));
}
}
for (next of nextNodes) {
const route = next();
if (route !== undefined) {
return route;
}
}
}
const routeTaken = bfs([], dataset, 'a3b1');
console.log(routeTaken);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment