I am attempting to teach myself how to write recursive functions and someone suggested trying to convert loops into recursions. So I am trying to change the first for loop function into a recursive function. Here is my code:
// Function that uses for loop.
function onlyOne(value1, value2, value3) {
var array = [value1, value2, value3];
var count = 0;
for(var i = 0; i < array.length; i++) {
if(!!array[i] === true) {
count ++;
}
} if(count === 1) {
return true;
} else {
return false;
}
}
// Function that uses recursion.
function onlyOne2(a, b, c) {
var array = [a, b, c];
var count = 0;
var numTrue = 0;
if(!!array[count] === true) {
numTrue++;
}
if(count === array.length-1) {
if(numTrue === 1) {
return true;
} else {
return false;
}
}else {
count++;
return onlyOne2(a, b, c);
}
}
console.log(onlyOne2(true, false, false));
The purpose of each function is to return true if there is exactly one argument that is truthy. Otherwise the function returns false. The for loop function works properly. However, when I use the recursive function I get the error: Maximum call stack size exceeded. I was wondering what I am doing incorrectly. Thank you for your help!