Hi there, I am going through this javascript practice module and I am having a hard time wrapping my head around finding the length in the exercise below. I have posted the solution and am trying to logically understand it. here are my questions:
why are we initially setting len = -1; ?
-why negative one as opposed to other numbers.
Also, i am hoping someone may be able to explain exactly what this bit of code is saying?
- if (len == -1) {
len = i;
} else {
len = i - len + 1
}
thank you for any help and insights you may have! The question and code are below:
Write a function subLength()
that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 0.
const subLength = (str, char) => {
let charCount = 0;
let len = -1;
for (let i=0; i<str.length; i++) {
if (str[i] == char) {
charCount++;
if (charCount > 2) {
return 0;
}
if (len == -1) {
len = i;
} else {
len = i - len + 1
}
}
}
if (charCount < 2) {
return 0;
}
return len;
};
console.log(subLength(‘abra’, ‘a’))