Reputation: 286
I'm working on CoderByte's beginner JavaScript challenge. My code works in the "true" cases, but as soon as I add an else clause to handle the "false" cases, it begins to misbehave.
The challenge: write a function ABCheck(str) to take the str parameter being passed and return the string true if the characters a and b are separated by exactly 3 places anywhere in the string at least once (ie. "lane borrowed" would result in true because there is exactly three characters between a and b). Otherwise return the string false.
Observations: if I remove the portion, the code works no matter what. But if I add a clause to handle the false cases, I feel like the counter breaks. For example, with the false portion, it works if (AxxB) is at the very beginning of the string, but it then returns false even if it's later in the string (zAxxB). Perhaps the counter is breaking, or I have the else clause in an incorrect spot? Something along those lines.
Thanks for any tips and for being patient with a beginner!
function ABCheck(str) {
//normalizes the string into an array without spaces
var arr = str.toLowerCase().split("").join("").replace( /\s/g, "")
//searches the entire string for the substring and returns true if it's found
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf('a') != -1 && arr[i+3].indexOf('b') != -1){
return true
}
//returns false if substring doesn't exist in string
else{
return false
}
}
}
ABCheck(readline());
Upvotes: 2
Views: 3766
Reputation: 9044
You should put return false;
out of for(var i = 0; i < arr.length; i++){...}
loop.
Upvotes: 1
Reputation: 25892
That is because for the first time only when it doesn't find the condition arr[i].indexOf('a') != -1 && arr[i+3].indexOf('b') != -1
to be true
it returns false
and function is over.
function ABCheck(str) {
var arr = str.toLowerCase().split("").join("").replace( /\s/g, "")
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf('a') != -1 && arr[i+3].indexOf('b') != -1){
return true
}
}
return false;
}
So it will check any time if the condition will be true it will return true
other wise after the for
loop it will return false
.
Note:- I think .split("").join("")
is unnecessary work.
Upvotes: 2