Incrementing a counter in recursive function calls

懵懂的女人 提交于 2019-12-23 01:53:18

问题


I'm struggling on how to increment a basic counter in javascript.

What do I want to achieve ?

I need a counter inside a foreach loop. The goal is to be able to count each time the //Write smthg is triggered.

Below is the updated version of the code I'm using. For the moment, it returns weird sequences of numbers. I guess it is resetted each time the recursive loop is triggered. I do not know how to correct it, suppose it's a basic javascript problem but as I'm learning through experimenting and on my own, I sometimes need to ask question to the community.

function walk(dir, counter = 0) {

  fs.readdirSync(dir).forEach(file => {

    let fullPath = path.join(dir, file);

    if (fs.lstatSync(fullPath).isDirectory()) {
      counter = walk(fullPath, counter);
      walk(fullPath, counter);
      console.log('dir');
    } else {
      let size = fs.statSync(fullPath).size; // Get size of file
      listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
      ++counter;
      console.log(counter);
    }

  });
  return counter;
}

walk(copyFrom); // Starts function "walk"

Sequences obtained :

2,3,4,5,6,7,dir,5,6,8,9,10,11,12,13,dir,11

Here is the complete answer

function walk(dir) {
  let n = 0;

  function walk(dir) {

    fs.readdirSync(dir).forEach(file => {

      ++n;
      console.log(n);
      let fullPath = path.join(dir, file);

      if (fs.lstatSync(fullPath).isDirectory()) {
        --n;
        walk(fullPath);
        console.log('dir');
      } else {
        let size = fs.statSync(fullPath).size; // Get size of file
        listFiles.write(fullPath + " (" + size + ")\n"); // Write file path and size into copyList.xml
      }

    });
  }
  return walk(dir);
}

回答1:


Use a helper. The function walk makes the lexical variable n and a function walk that shadows the called fucntion for the duration of the recursive calls. It may have the original content of walk and the outer function just returns the result of calling it as itself was called.

function walk(dir) {
  let n = 0; //Counter variable
  function walk(dir) {
    dir.forEach(file => {
      ++n;
      console.log(n);
      if (true) {
        //Recurse loop
      } else {
        //Write smthg
      }
    });
  }
  return walk(dir);
}



回答2:


So, your issue is as follows:

Your counter will reset to 0 each time you recurse. So your numbers can go something like so: 0, 1, 0, 2, 0, 1, 2, 3, 3, ...etc. If you want to have an iterator counting total number of iterations, you'll need to pass your counter into the function and default it to 0 (for the first time walk is called), like so:

var files = ["dir1-file1", "dir1-file2", ["dir1-sub1-file1"], "dir1-file3", ["dir1-sub2-file1", ["dir1-sub2-subsub1-file1"]]];

function walk(dir, counter = 0) {
  dir.forEach(file => {
    if (Array.isArray(file)) {
      // pass counter in to recursed function call
      // set current function counter to the result of the recursed function calls
      counter = walk(file, counter);
    } else {
      //Write smthg
      ++counter;
      console.log(counter);
      console.log(file);
    }
  });
  // return the counter for parent
  return counter;
}

walk(files);


来源:https://stackoverflow.com/questions/50282360/incrementing-a-counter-in-recursive-function-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!