Function subLength()

I’m having trouble understanding the logic for the subLength() function in the practice section for arrays, loops, objects and iterators for the full-stack engineer path. Can someone explain it to me step by step?

// 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;
};
1 Like

I approached this problem from the false case perspective and deal with that issue, first.

const subLength = function (str, chr) {
  let y = str.split('').filter(x => x === chr)
  if (y.length !== 2) return 0
  // ...
}

It’s a bit convoluted, perhaps, but it weeds out all the cases for this type of return.

Now we can get into the logic knowing that we have exactly two instances of chr in str.

  const m = str.indexOf(chr)
  const n = str.lastIndexOf(chr)
  y = str.substr(m, n)

That gives us our return value…

  return y.length
}

Now I may have cheated and not did the character count as you did, my bad, but that is the right idea. Only thing to change there is > 2. We also want to catch less than 2, as well; ergo, !== 2. That is where your logic should escape the loop and begin anew.

Use the loop you have for only determining whether to return 0, or not. Now work on the logic of the string we know to exist with a length of at least 2. Locate the index of those two characters and capture them and everything in between.