js build dependency graph from array [{id:1, childIds:["2","12"]}, {id:2,…
- User
js build dependency graph from array [{id:1, childIds:["2","12"]}, {id:2, childIds:["3","5"]}, {id:3, childIds:[]} ]
- Assistant
You can create a dependency graph from the given array by creating a mapping of each node and its children. Here's a JavaScript function that constructs the graph and prints it in a readable format:
const data = [ { id: 1, childIds: ["2", "12"] }, { id: 2, childIds: ["3", "5"] }, { id: 3, childIds: [] } ]; // Function to build the dependency graph function buildDependencyGraph(data) { const graph = {}; // Initialize the graph with nodes data.forEach(node => { graph[node.id] = { id: node.id, children: [] }; }); // Populate the children data.forEach(node => { node.childIds.forEach(childId => { if (graph[childId]) { graph[node.id].children.push(graph[childId]); } }); }); return graph; } // Build the graph const dependencyGraph = buildDependencyGraph(data); // Function to print the graph in a readable format function printGraph(graph) { for (const key in graph) { const node = graph[key]; console.log(`Node ID: ${node.id}, Children: ${node.children.map(child => child.id).join(', ')}`); } } // Print the dependency graph printGraph(dependencyGraph); - User
how to find root nodes for selected nodes in graph
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.