JS challenge sublength()

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.

// Write function below
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 dont understand the len part where its was set as len = -1 and where len = i - len + 1 . Would someone explain why we do this?

Hi!

I think it’s almost always a great idea to work out algorithm problems on a paper or a whiteboard (the extra little bit of space helps).

If you have have a visual representation of how the elements are shifting, it’s easier to see and intuit where these numbers are coming from. If you can visualize what the code is doing, it’s much simpler to find the right bounds. Whereas if you’re coming up with bounds first it can be disconcerting if you’re not used to it.

And in the future have this for reference :slight_smile: [How to] Format code in posts