Help for this complex question's solution please

Hello everyone and thanks in advance for your help if you share your time for this solution.I am currently having job interviews for front end and I came across with the question today in the interview.I could’t figure out anything. Thanks a lot.


var FileTreeNode = function(nodeId, name, type) {
  var children = [];

  this.nodeId = nodeId;
  this.name = name;
  this.type = type;
  this.parentNode = null;

  this.setParent = function(parentNode) {
    this.parentNode = parentNode;
  };
  this.addChild = function(node){
    if (this.type !== 'DIRECTORY') {
      throw "Cannot add child node to a non-directory node";
    }
    children.push(node);
    node.setParent(this);
  };
  this.getChildren = function() {
    return children;
  };
};

var FileTree = function() {
  this.nodes = [];

  this.getRootNodes = function() {
    var result = [];
    for (var i = 0; i < this.nodes.length; i++) {
      if (!this.nodes[i].parentNode) {
        result.push(this.nodes[i]);
      }
    }
    return result;
  };
  this.findNodeById = function(nodeId) {
    for (var i = 0; i < this.nodes.length; i++) {
      if (this.nodes[i].nodeId === nodeId) {
        return this.nodes[i];
      }
    }
    return null;
  };
  this.createNode = function(nodeId, name, type, parentNode) {
    var node = new FileTreeNode(nodeId, name, type);
    if (parentNode) {
      parentNode.addChild(node);
    }
    this.nodes.push(node);
  }
};

function createFileTree(input) {
  var fileTree = new FileTree();

  for (var i = 0; i < input.length; i++) {
    var inputNode = input[i];
    var parentNode = inputNode.parentId ? fileTree.findNodeById(inputNode.parentId) : null;
    fileTree.createNode(inputNode.id, inputNode.name, inputNode.type, parentNode);
  }

  return fileTree;
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

Thank you so much :slight_smile:

la solucion es esta

export function createFileTree(input) {
var fileTree = new FileTree();
var parentLinks = {};

for (const inputNode of input) {
parentLinks[inputNode.id] = inputNode.parentId ? inputNode.parentId : null;
fileTree.createNode(inputNode.id, inputNode.name, inputNode.type, null);
}

for(var nodeId in parentLinks) {
var node = fileTree.findNodeById(+nodeId);
var parentNode = fileTree.findNodeById(parentLinks[nodeId]);

if(parentNode) {
  node.setParent(parentNode);
  parentNode.addChild(node);
}

}

return fileTree;
}