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 what the next if condition is doing - please be more specific - there's 4 if statements. – fdomn-m Commented Jan 31 at 14:18
  • 2 Have you stepped through the code in a debugger to observe what each operation is doing? – David Commented Jan 31 at 14:19
  • Maybe this will help: charCount is the number of times that char appears. It's not the len/difference. You have a rule that if char appears more than 2 times then return 0. so if charCount > 2 does just that. – fdomn-m Commented Jan 31 at 14:19
  • You probably mean the if (len==-1) check. len==-1 means this is the first time that a char has been matched, so sets "len" to the current index. The else means it's the second time (as 3rd will abort) so calculates current position i minus previous position len then adjusts for including the char in the count. It's succinct, but not ideal/good practice as it means len has three meanings: char not found, position of first char, final result. – fdomn-m Commented Jan 31 at 14:21
  • Thanks all for your input. Brain is totally frazzled now. I’ll take another look on Monday. – Steven Llewellyn Commented Jan 31 at 17:21
Add a comment  | 

1 Answer 1

Reset to default 0

Here 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