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 forest = [];

while (stack.length !== 0) {
  let currentItem = stack.pop();
  currentItem.children = [];
  currentItem.type = 'question';
  
  if (!nodeSeen[currentItem.id]) {
  	forest.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;
    }
  }
}


// ordering

let orderingStack = [forest[0]];
let ordering = [];

while (orderingStack.length !== 0) {
	let currentItem = orderingStack.pop();
  ordering.push(currentItem);
  for (child of currentItem.children) {
  	orderingStack.push(child);
  }
}

ordering
debugger