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');
3
  • also the code runs like 1000 times not sure why if there is any help on that, that would be nice Commented Jan 14, 2018 at 19:13
  • Not certain what you are trying to achieve? What is the issue with the code at Question? Commented Jan 14, 2018 at 19:18
  • The call has a missing quote. Commented Jan 14, 2018 at 19:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yes you absolutely correct I did get confused by the n and pathLength I realised that after.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.