0

I have some variables that are not included in the function but just outside of where they are created. I know I can pass them as parameters however I am looking for a more elegant method.

Code:

Tree.prototype.add = function(path){
var pathSplit = path.split('/');
//gets the length of the path
const pathLength = pathSplit.length;
//this compares the path to the nodes/directories
let compare = (currentNode, n) => {
    console.log(n);
    if(n == pathLength -1){
        console.log(pathLength);
        //create a new node with file name as data
        var nodeFile = new Node(pathSplit[n]);
        //adds the file name onto the the node
        currentNode.children.push(nodeFile);
        //sets the node parent to the currentNode
        nodeFile.parent = currentNode;
    }else{
        //console.log('THIS IS RUN');
        var newNode = () => this.traversalBF(currentNode, pathSplit[n]);
           //console.log(newNode);
           compare(newNode, n++);
       };

   };
   compare(this._root, 0);
   };

the variable PathLength is considered to be 0 inside the compare function. however it should be 3 when it is called:

tree.add('one/two/three');
Bharata
  • 13,509
  • 6
  • 36
  • 50
help please
  • 25
  • 2
  • 11

2 Answers2

1

The problem is that in your recursive call you pass the value of n++. Note that this passes the value of n before it is increased. So you get an infinite recursion-chain where the path length is never reached.

Instead do:

        compare(newNode, n+1);

Note: The value of pathLength is never 0. You log both n and pathLength at different locations in your code, and so you might have confused one for the other. It is n that is 0.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

PathLength is considered to be 0 inside the compare function. however it should be 3 when it is called

pathLength is declared using const. The value of pathLength cannot be changed. See

You can declare the variable using let and within the function change the value of the variable.

guest271314
  • 1
  • 15
  • 104
  • 177