Does my code work efficiently vs View Solution? - JavaScript Course

Hey Everyone,

My Question is related to this question in the Javascript Course.

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.

Examples:

subLength('Saturday', 'a'); // returns 6
subLength('summer', 'm'); // returns 2
subLength('digitize', 'i'); // returns 0
subLength('cheesecake', 'k'); // returns 0

It would not let me pass with my code. When I was getting the same end result.

Also as far as speed and functionality are concerned which code should run faster and more accurately? I am just trying to wrap my head around it.

My Code

// Find distance beteen to matching letters (including matches)
const subLength = (word, letter) => {
  let amountFound = 0; // Claim Occurence Variable

  // Find Occurences
  for (char of word){
    if(char.toLowerCase() === letter.toLowerCase()){
      amountFound++
    };
  };

  // Only allow groups of 2 letters output otherwise 0
  if (amountFound === 2){
    return word.lastIndexOf(letter) - word.indexOf(letter) + 1;
  } else{
    return 0;
  };
};

Code I had to use to move on (View Solution)

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

My code is definitely slower.