JSFiddle - React, Tailwind, and code Playground

by jrab227

JavaScript

var j = [
	{id: 1, connected:[3, 2]}, {id: 2, connected: ['end'] },
	{id: 3, connected: [4, 5]}, {id: 4, connected:[]}, {id: 5, connected:[]}];

let hash = j.reduce((agg, next) => {
	agg[next.id] = next
  return agg;
}, {});

let stack = [j[0]];
j[0].depth = 1;

let nodeSeen = {};
let ordering = [];

while (stack.length !== 0) {
  let currentItem = stack.pop();
  currentItem.children = [];
  currentItem.type = 'question';
  
  if (!nodeSeen[currentItem.id]) {
  	ordering.push(currentItem);
    nodeSeen[currentItem.id] = true;
  }
  for (child of currentItem.connected) {
  	if ((child !== 'end')) {
    	let newBranch = { depth: currentItem.depth + 1, children: [], type: 'branch' };
      stack.push(hash[child]);
      
      hash[child].depth = currentItem.depth + 1;
      
      newBranch.children.push(hash[child]);
      currentItem.children.push(newBranch);
      nodeSeen[child] = true;
    }
  }
}
console.log(JSON.Stringify(ordering))

alert(ordering)