admin管理员组文章数量:1313615
I can't understand a coding solution I've been give. I'm new to coding so trying to wrap my head around it. Hopefully someone can help.
Coding exercise:
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.
I understand the for loop iterates over the string and if the string index matches the character then it increases the charCount by 1. The part I can't understand is what the next if condition is doing. How is it determining the length between two index numbers?
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('Saturday', 'a')
);
I can't understand a coding solution I've been give. I'm new to coding so trying to wrap my head around it. Hopefully someone can help.
Coding exercise:
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.
I understand the for loop iterates over the string and if the string index matches the character then it increases the charCount by 1. The part I can't understand is what the next if condition is doing. How is it determining the length between two index numbers?
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('Saturday', 'a')
);
Share
Improve this question
edited Jan 31 at 14:20
mplungjan
178k28 gold badges181 silver badges240 bronze badges
asked Jan 31 at 14:16
Steven LlewellynSteven Llewellyn
111 bronze badge
5
|
1 Answer
Reset to default 0Here is a version with no ifs. See if you can understand it. It uses flatMap and the ternary operator
const subLength = (str, char) => {
const indices = [...str].flatMap((c, i) => (c === char ? i : [])); // using flatMap instead of filter
return indices.length === 2 ? indices[1] - indices[0] + 1 : 0; // if exactly two results calculate the difference including start and end.
};
// Test cases
console.log(subLength('hello', 'l')); // 2 ("ll")
console.log(subLength('abcdabcd', 'b')); // 5 ("bcdab")
console.log(subLength('abababa', 'a')); // 0 (more than 2 occurrences)
console.log(subLength('xyz', 'x')); // 0 (only 1 occurrence)
console.log(subLength('banana', 'n')); // 3 ("nan")
本文标签: JavaScript function with a for loop If condition doesn39t make senseStack Overflow
版权声明:本文标题:JavaScript function with a for loop. If condition doesn't make sense - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741914826a2404664.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
if
statements. – fdomn-m Commented Jan 31 at 14:18charCount
is the number of times thatchar
appears. It's not the len/difference. You have a rule that ifchar
appears more than 2 times then return 0. soif charCount > 2
does just that. – fdomn-m Commented Jan 31 at 14:19if (len==-1)
check. len==-1 means this is the first time that a char has been matched, so sets "len" to the current index. Theelse
means it's the second time (as 3rd will abort) so calculates current positioni
minus previous positionlen
then adjusts for including thechar
in the count. It's succinct, but not ideal/good practice as it meanslen
has three meanings: char not found, position of first char, final result. – fdomn-m Commented Jan 31 at 14:21