Decision Tree Test

Test for FormHero interview. All code is original and sample only. Private license, no permission to copy, reproduce, or own.

by Joshua Koudys

JavaScript

// Script setup - consider these constant
const nodes = [{
	uuid: 111,
  type: 'bigchoice',
}, {
	uuid: 112,
  type: 'checkboxes',
}, {
	uuid: 113,
  type: 'decision',
}, {
	uuid: 211,
  type: 'checkboxes',
}, {
	uuid: 311,
  type: 'legal',
}];
let nodeCount = nodes.length;
const sourceData = { nodes };
let currentPathFromRoot = [111, 112, 211]

function filterLogicNodesFromPath(path) {
	return path.filter(({ type }) => type !== 'decision');
}

/**
 * Changes start here
 */

// TODO: Refactor this to make it nicer. Use some destructurng & array methods instead.
function getNodeByUuid(uuid) {
  for (let i = 0; i < nodeCount; i++) {
    if (sourceData.nodes[i].uuid == uuid) return sourceData.nodes[i];
  }
  return null;
}

// TODO: Clean out anything useless, and get the list of nodes.
// This should take the current path, and return all the nodes, without
// decisions.
function getPathNodeListFromRoot() {
  // var path = getMaxPathFromNode(startNode, [], true);
  let path = [...currentPathFromRoot];
  let pathBlockedAtBranch;
  let blockingNode;
  for (let j = 0, rawPathLength = path.length; j < rawPathLength; j++) {
    const node = sourceData.nodes.find(({ uuid }) => uuid === path[j]);

    if (node.type == 'decision') {
      indexOfFirstBlockedBranch = j;
      pathBlockedAtBranch = node;
      blockingNode = pathBlockedAtBranch;
    }
  }

  path = filterLogicNodesFromPath(path);

  const pathLength = path.length;
  for (let i = 0; i < pathLength; i++) {
    path[i] = sourceData.nodes.find(({ uuid }) => uuid === path[i]);
  }
  
  return path;
}

/**
 * Test executions
 * No need to edit
 */
document.body.appendChild(Object.assign(document.createElement('div'), {
  textContent: `Node 211 is: ${getNodeByUuid(211).type}`,
}));

document.body.appendChild(Object.assign(document.createElement('div'), {
  textContent: `Decision tree is: ${JSON.stringify(getPathNodeListFromRoot())}`,
}));