Hi there!
I’m really struggling to understand the following code…
The question: 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.
the code I’m analysing:
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;
};
I’ve been playing around with the code and for the life of me cannot figure out what does the Len represent?
I think it has something to do with the length of where the first index meets the condition but I don’t understand why it has to start at -1? when I replace -1 with 0, the outputs still the same.
Would really appreciate anyone who can help!
Thank you!
link: