Employee relation

by rishul matta

HTML

<h2>Eg 1:</h2>
<div id="eg1"></div>
---------------------------------
<h2>Eg 2:</h2>
<div id="eg2"></div>
---------------------------------
<h2>Eg 3:</h2>
<div id="eg3"></div>

JavaScript

class OrganizationTree {
  constructor() {
    this.start = [];
    this.mapOfEmployeeIdsInTheTree = {};
  }

  insertEmployee(employeeNode) {
    // Traverse the tree and insert the node for the child of the manager
    let isNodeInserted = false;
    if (this.start.length === 0) {
      this.mapOfEmployeeIdsInTheTree[employeeNode.id] = true;
      this.start.push(employeeNode);
      return true;
    }

    if (this.mapOfEmployeeIdsInTheTree[employeeNode.managerId]) {
      // if the manager is in the tree only then do the iteration and insertion
      for (const startingNode of this.start) {
        isNodeInserted = this.findManagerAndInsertEmployeeNode(startingNode, employeeNode);
        if (isNodeInserted) {
          return true;
        }
      }
    } else {
      // this means that the manager of the node is not yet in the tree so insert it at the root level

      this.start.push(employeeNode);
      this.mapOfEmployeeIdsInTheTree[employeeNode.id] = true;
      return true;
    }
  }

  normalizeTree() {
    // there can be a situation where we have a employee at the root level but its manager is also present at some
    // nth depth level so for such nodes we will just remove them from the start array
    // as the manager node already is pointing to this node via the children array property of EmployeeNode
    // only keep those nodes at root level whose managers are not in the tree

    const parentNodesToMerge = this.start.filter(startingEmployeeNode => this.mapOfEmployeeIdsInTheTree[startingEmployeeNode.managerId]);

    // only keep the ones which dont have their managers in the org
    this.start = this.start.filter(startingEmployeeNode => !this.mapOfEmployeeIdsInTheTree[startingEmployeeNode.managerId]);

    let index = 0;
    while (parentNodesToMerge.length !== 0) {
      const isParentFound = this.insertEmployee(parentNodesToMerge[index]);
      if (isParentFound) {
				parentNodesToMerge.splice(index, 1);
      } else {
      	if (index + 1...