skip to Main Content

I’m supposed to turn the following function into a while loop. The function is supposed to count all the e’s that appear in a certain string. Here’s the function using a for loop:

function eCounter(word) {
  let count = 0;

  for (let index = 0; index < word.length; index++) {
    let char = word[index];
    if (char === "e" || char === "E") {
      count += 1;
    }
  }

  return count;
};

Here’s my code:

function eCounter(word) {
  let count = 0
  let index = 0;
  let char = word[index];
  
while (char === "e" || char === "E") {
index+= count;
}
return count;
}
};

console.log(eCounter("apple")); // => 1
console.log(eCounter("appleapple")); // => 2
console.log(eCounter("Appleee")); // => 3

If count and index are both 0, and char is defined, I’m not sure what to do next. When I console.log the strings, all three return zero.

Any help I can get will be greatly appreciated.

I tried putting all of the code from the for loop into a while loop. I figured if I rearranged the for loop code into a while loop, it would return the number of e’s in each string. But when I run the code, all three counts return 0.

3

Answers


  1. It’s similar to for loop

    function eCounter(word) {
      let count = 0
      let index = 0;
      while (index < word.length) {
        const char = word[index]
        if (char === "e" || char === "E") {
          count++
        }
        index++
      }
      return count;
    }
    Login or Signup to reply.
  2. try this

       function eCounter(word) {
      let count = 0
      let index = 0;
      let char = word.split('');
      
    while (char[index]) {
    
    if(char[index] === 'e' || char[index] === 'E'){
      count = count + 1;
    }
    
    index++;
    }
    return count;
    }
    };
    
    Login or Signup to reply.
  3. Loop by the char index and increment it with ++ during reading the current character:

    function eCounter(word) {
      let count = 0, index = 0;
      while (index < word.length) {
        const char = word[index++];
        (char === "e" || char === "E") && count++;
      }
      return count;
    }
    
    console.log(eCounter('Evergrande'));

    Some more fancy variant:

    function eCounter(word) {
      let count = 0, index = 0, char;
      while (char = word[index++]) (char === "e" || char === "E") && count++;
      return count;
    }
    
    console.log(eCounter('Evergrande'));

    Can be even an one-liner:

    const eCounter = (word, index = 0, count = 0, char = null) => { while (char = word[index++]) (char === "e" || char === "E") && count++; return count};
    
    console.log(eCounter('Evergrande'));

    Btw you can almost always replace the loop with Array::reduce:

    const eCounter = word => [...word].reduce((r, char) => char === "e" || char === "E" ? r + 1 : r, 0);
    
    console.log(eCounter('Evergrande'));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search