Seeking assistance with my JavaScript recursion program that is not functioning as expected. The goal is to extract words from a text file and output the count of words, lines, and characters. I am uncertain where my mistake lies, so any guidance on code modification would be greatly appreciated. Below is the JavaScript code in question:
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."
);
Below is the content of the text.txt file:
I was running to the zoo.