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;
};
Can someone explain the len=-1 and how to find length between character part in this question please?
CodePudding user response:
It is used as initial value. The initial value of 'len' needs to be outside the possible range of 'len' otherwise you cannot set the first position of the first occurrence of the char.
E.g. if 'len' is initialized with 0 it will be assumed that the first occurrence of the char is at position 0.
CodePudding user response:
In your function the second line, you declare that len
variable to -1
. The intent is to use a number, that impossible to return (you defined 0 as no, or too many occurences, and every other number could be a valid length between those two occurences).
If you've found the first occurence of the specific character, you should remember it, where to start the counting. This is when it checks for the initial value of -1.
When the second character is found, this len
variable is something other than -1, so the else branch is executed.
if(len == -1) {
len = i; // found the first occurence, save its position
} else {
len = i - len 1; // not the first occurence, calculate the length
}
CodePudding user response:
variable
len
has been initialized with -1 because this value is not going to occur as index or length while iterating over the String
str
. Later,
len
is initialized with the index at which that char occurs first time in String
str
by checking if
len
is -1 otherwise it would be second occurrence of same
char
(else condition).