Home > Enterprise >  Why is my javascript recursion code not calculating the number of lines words and characters in a te
Why is my javascript recursion code not calculating the number of lines words and characters in a te

Time:10-17

Need help on why my recursion program in javascript is not working. It is supposed to take the words from the text file and display the number of words, lines and characters in it. Please help me modify my code or tell me where my mistake is because I do not know where. Here is the javascript code:

var fs = require("fs");
var text = fs.readFileSync("text.txt", "utf8");
function countLines(text) {
  if (text == "") {
    return 0;
  } else {
    return 1   countLines(text.substring(text.indexOf("\n")   1));
  }
}
function countWords(text) {
  if (text == "") {
    return 0;
  } else {
    return 1   countWords(text.substring(text.indexOf(" ")   1));
  }
}
function countCharacters(text) {
  if (text == "") {
    return 0;
  } else {
    return 1   countCharacters(text.substring(1));
  }
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
  "There are "  
    lineCount  
    " lines, "  
    wordCount  
    " words, and "  
    characterCount  
    " characters in the file."
);

This is the text.txt file:

I was running to the zoo.

CodePudding user response:

Your issue is blindly recursing without checking the result of indexOf, which is -1 when the target isn't found

so

text.substring(text.indexOf(" ")   1)

becomes

text.substring(-1   1)

in other words

text.substring(0)

So, you infinitely recurse the last word (and line, for that matter)

If .indexOf returns -1, you should return 1

Note: I removed the unnecessary else in your code - no need for else when the if returns a value - this make for cleaner code (in my opinion, you're welcome to use else if you must

I've shown two different ways to test indexOf

var text = "I was running to the zoo.";

function countLines(text) {
  if (text == "") {
    return 0;
  }
  const index = text.indexOf("\n");
  if (index  < 0) {
    return 1;
  }
  return 1   countLines(text.substring(index   1));
}

function countWords(text) {
  if (text == "") {
    return 0;
  }
  const index = text.indexOf(" ")   1;
  if (index) { // since we've added 1, a "not found" -1 would be 0 here, and be falsey
    return 1   countWords(text.substring(index));
  }
  return 1;
}

function countCharacters(text) {
  if (text == "") {
    return 0;
  } 
  return 1   countCharacters(text.substring(1));
}
var lineCount = countLines(text);
var wordCount = countWords(text);
var characterCount = countCharacters(text);
console.log(
  "There are "  
  lineCount  
  " lines, "  
  wordCount  
  " words, and "  
  characterCount  
  " characters in the file."
);

  • Related