Last active
June 16, 2017 02:44
-
-
Save daneharrigan/55a2ce5dfb799446e3c58d4fa63ffb53 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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